# Agora Agent (/work/agora)

<Callout type="warn" title="Status">
Prototype, and an unfinished one. Built as a submission for a Logos Lambda Prize (LP-0008). The parts exist; they are not yet joined into a trade that completes. This page says which is which.
</Callout>

| Role | Year | Kind | Try it |
| --- | --- | --- | --- |
| Concept, protocol design, engineering | 2026 | Agent infrastructure | [Source on GitHub](https://github.com/Beach-Bum/agora-agent) |

| | |
| --- | --- |
| **3** | contracts in Rust: escrow, identity, reputation |
| **24 + 37** | tests that run: on the contracts, and on the agent |
| **10 / 100** | default spending limits for an agent, per payment and per day |

## The problem [#the-problem]

If agents are going to pay each other for work, three things usually sit in the middle: a hosted model that does the reasoning, a public chain where every payment can be read, and a company that can switch the whole thing off.

I wanted to see how far an agent marketplace could get with none of the three.

This is the agent marketplace. Agora Bazaar, a marketplace for people on the same stack, is a separate project.

## What I built [#what-i-built]

- **An agent** that runs continuously as a seller and, on request, as a buyer: it listens for requests, decides whether to offer, delivers, and gets paid.
- **A wallet with a policy.** The agent holds its own key and can only spend inside limits its owner sets.
- **Three contracts, as models.** Escrow holds the payment, identity names the agent, reputation records how its trades went. They are plain Rust state machines with no chain SDK; they model the rules and are not deployed.
- **A module and interface for Logos Basecamp,** in C++ and QML, with views for the marketplace, buying, selling, the wallet and an activity feed.

## How it is structured [#how-it-is-structured]

<Mermaid caption="One agent node. The three Logos services replace the hosted model, the public chain and the operator." chart={`flowchart LR
  O[Owner<br/>sets limits] --> A[Agent<br/>perceive, reason, act]
  L[Local model] --> A
  A --> M[Messaging<br/>discover and negotiate]
  A --> B[Blockchain<br/>identity, escrow, payment]
  A --> S[Storage<br/>deliver and verify]
`} />

The agent is Python, about 6,800 lines. The contracts are Rust, about 1,500 lines. The Basecamp module and interface are C++ and QML.

## How a trade is meant to be made safe [#how-a-trade-is-meant-to-be-made-safe]

Neither agent trusts the other, so the escrow contract is meant to.

| Step | What the contract code does |
| --- | --- |
| **1. Lock** | Records the payment plus a bond of 10% of it, and the hash the seller commits to. |
| **2. Deliver** | The seller reveals the delivery. If its hash does not match the commitment, the trade is marked disputed without anyone having to ask. |
| **3. Release** | The buyer releases the payment and gets the bond back. |
| **4. Or time out** | If the seller never delivers, the buyer takes back the payment and the bond after the deadline. |

The bond is there so that disputing is not free: a buyer who disputes an honest delivery has something to lose.

```rust title="contracts/escrow/src/lib.rs"
pub fn notify_delivery(
    &mut self,
    caller_id:          &AgentId,
    escrow_id:          &str,
    actual_output_hash: String,
    logos_storage_cid:  String,
    ts:                 TimestampMs,
) -> Result<DeliveryOutcome> {
    let record = self.escrows.get_mut(escrow_id)
        .ok_or(ContractError::EscrowNotFound)?;

    if &record.seller_id != caller_id {
        return Err(ContractError::UnauthorisedCaller);
    }
    if record.status != EscrowStatus::Pending {
        return Err(ContractError::EscrowNotPending);
    }
    if ts > record.timeout_ms {
        return Err(ContractError::EscrowExpired);
    }

    // FIX-2: Verify hash matches commitment (which includes buyer nonce)
    if actual_output_hash != record.delivery_hash_commitment {
        record.status = EscrowStatus::Disputed;
        record.dispute_reason = Some("seller revealed hash does not match commitment".into());
        // Keep what the seller actually revealed as evidence for the arbiter.
        record.actual_output_hash = Some(actual_output_hash);
        record.logos_storage_cid  = Some(logos_storage_cid);
        return Ok(DeliveryOutcome::Disputed);
    }

    record.actual_output_hash = Some(actual_output_hash);
    record.logos_storage_cid  = Some(logos_storage_cid);
    record.status             = EscrowStatus::Delivered;
    record.delivered_ts       = Some(ts);  // FIX-3: record delivery time for grace period

    Ok(DeliveryOutcome::Delivered)
}
```

Three guards, then the reveal. The mismatch branch used to change the record and then return an error. On a real chain an error undoes the changes made before it, so the dispute would never have been recorded. It now returns success with a "disputed" result, and keeps what the seller revealed as evidence.

### Does the money add up? [#does-the-money-add-up]

When I first read this contract, the lock was bookkeeping: it credited the buyer and debited the same amount, so nothing was held. Now a payment and its bond move into a held account, every payout leaves from it, and a forfeited bond goes to a treasury account. This test walks all five ways a trade can end and checks, after every step, that the four balances are exactly what they should be and add up to what was paid in.

```rust title="contracts/escrow/src/lib.rs"
#[test]
fn test_funds_conserved_across_all_terminal_states() {
    let locked = AMOUNT + BOND;
    let buyer_after_lock = BUYER_FUNDS - locked;

    // 1. Release: seller is paid, buyer gets the bond back.
    let mut c = EscrowContract::new(None);
    let eid = make(&mut c);
    assert_balances(&c, buyer_after_lock, 0, locked, 0);
    c.notify_delivery(&SELLER.into(), &eid, HASH.into(), "Qm".into(), T_DELIVERED).unwrap();
    assert_balances(&c, buyer_after_lock, 0, locked, 0);
    c.release(&BUYER.into(), &eid, HASH.into(), NONCE.into(), 2).unwrap();
    assert_eq!(c.get(&eid).unwrap().status, EscrowStatus::Released);
    assert_balances(&c, BUYER_FUNDS - AMOUNT, AMOUNT, 0, 0);
    assert_settled(&mut c, &eid);

    // 2. Refund after timeout: buyer gets amount + bond back.
    let mut c = EscrowContract::new(None);
    let eid = make(&mut c);
    assert_eq!(c.refund(&BUYER.into(), &eid, TIMEOUT - 1, 2), Err(ContractError::EscrowNotExpired));
    assert_balances(&c, buyer_after_lock, 0, locked, 0);
    assert_eq!(c.refund(&BUYER.into(), &eid, TIMEOUT, 2), Ok(locked));
    assert_eq!(c.get(&eid).unwrap().status, EscrowStatus::Refunded);
    assert_balances(&c, BUYER_FUNDS, 0, 0, 0);
    assert_settled(&mut c, &eid);

    // 3. Auto-claim after grace: seller is paid, buyer's bond goes to treasury.
    let mut c = EscrowContract::new(None);
    let eid = make(&mut c);
    c.notify_delivery(&SELLER.into(), &eid, HASH.into(), "Qm".into(), T_DELIVERED).unwrap();
    c.claim_after_grace(&SELLER.into(), &eid, T_DELIVERED + DELIVERY_GRACE_MS, 2).unwrap();
    assert_eq!(c.get(&eid).unwrap().status, EscrowStatus::AutoClaimed);
    assert_balances(&c, buyer_after_lock, AMOUNT, 0, BOND);
    assert_settled(&mut c, &eid);

    // 4. Dispute, seller at fault: buyer gets amount + bond back.
    let mut c = EscrowContract::new(None);
    let eid = make(&mut c);
    c.notify_delivery(&SELLER.into(), &eid, HASH.into(), "Qm".into(), T_DELIVERED).unwrap();
    c.open_dispute(&BUYER.into(), &eid, "bad output".into()).unwrap();
    assert_balances(&c, buyer_after_lock, 0, locked, 0);
    c.resolve_dispute(&ARBITER.into(), &eid, true, 2).unwrap();
    assert_eq!(c.get(&eid).unwrap().status, EscrowStatus::SlashedSeller);
    assert_balances(&c, BUYER_FUNDS, 0, 0, 0);
    assert_settled(&mut c, &eid);

    // 5. Dispute, buyer at fault: seller is paid, buyer's bond goes to treasury.
    let mut c = EscrowContract::new(None);
    let eid = make(&mut c);
    c.notify_delivery(&SELLER.into(), &eid, HASH.into(), "Qm".into(), T_DELIVERED).unwrap();
    c.open_dispute(&BUYER.into(), &eid, "false claim".into()).unwrap();
    c.resolve_dispute(&ARBITER.into(), &eid, false, 2).unwrap();
    assert_eq!(c.get(&eid).unwrap().status, EscrowStatus::SlashedBuyer);
    assert_balances(&c, buyer_after_lock, AMOUNT, 0, BOND);
    assert_settled(&mut c, &eid);
}
```

`assert_settled` then tries every entry point again on the finished trade and requires that none of them moves anything.

### Who sent this message? [#who-sent-this-message]

Messages between agents carried a signature that nothing checked, and the signature itself was not one another agent could verify. An agent's id is now its public key, messages are signed with Ed25519, and the check sits in a deliberate place: before the replay cache and before the rate limiter.

```python title="agent/logos/messaging.py"
nonce = msg["nonce"]
if not isinstance(nonce, str) or len(nonce) < 16:
    return False, "missing or short nonce"

# Authenticate the sender before touching any per-sender state.
signer_field = SIGNER_FIELD_BY_TYPE.get(msg["type"]) if isinstance(msg["type"], str) else None
if signer_field is not None:
    valid, reason = verify_message(msg)
    if not valid:
        return False, reason
    sender = msg[signer_field]
else:
    # Other message types (direct messages, topic messages, agent cards)
    # are not signed yet: their sender is unauthenticated.
    sender = msg.get("agentId") or msg.get("buyerId") or msg.get("sellerId") or ""
    if not isinstance(sender, str):
        return False, "sender id must be a string"

# FIX-6: Nonce replay check
if not nonce_cache.check_and_record(nonce):
    return False, "replay attack: nonce already seen"

# FIX-9: Rate limiting
if sender and not rate_limiter.allow(sender):
    return False, f"rate limit exceeded for {sender[:16]}"

return True, "ok"
```

The order matters. If the nonce were recorded first, anyone could send a forged message carrying a real sender's next nonce and so block the real one. A test sends exactly that forgery and then checks the real message still gets through.

## Keeping the agent on a leash [#keeping-the-agent-on-a-leash]

The agent holds its own key and spends only inside a policy its owner sets. This is the whole check, in the order it runs.

```python title="agent/core/daemon_wallet.py"
def check_spend(self, amount_nom: float, category: str,
                counterparty_rep: float = 1.0,
                escrow_timeout_ms: int = 60000,
                slash_bps: int = 500) -> tuple[bool, str]:
    """
    Check if a spend is allowed by the current policy.
    Returns (allowed, reason).
    """
    if self.policy.frozen:
        return False, "wallet frozen by user"

    if amount_nom > self._balance_nom:
        return False, f"insufficient balance: {self._balance_nom:.2f} NOM < {amount_nom:.2f} NOM"

    if amount_nom > self.policy.max_per_tx_nom:
        return False, f"exceeds per-tx limit: {amount_nom:.2f} > {self.policy.max_per_tx_nom:.2f} NOM"

    # Rolling 24h window
    self._prune_spend_window()
    daily_total = sum(amt for _, amt in self._spend_window)
    if daily_total + amount_nom > self.policy.daily_cap_nom:
        return False, f"exceeds daily cap: {daily_total:.2f} + {amount_nom:.2f} > {self.policy.daily_cap_nom:.2f} NOM"

    if category not in self.policy.approved_categories:
        return False, f"category '{category}' not approved"

    if counterparty_rep < self.policy.min_counterparty_reputation:
        return False, f"counterparty reputation {counterparty_rep:.2f} below minimum {self.policy.min_counterparty_reputation:.2f}"

    if escrow_timeout_ms > self.policy.max_escrow_timeout_ms:
        return False, f"escrow timeout {escrow_timeout_ms}ms exceeds max {self.policy.max_escrow_timeout_ms}ms"

    if slash_bps > self.policy.max_slash_bps:
        return False, f"slash risk {slash_bps}bps exceeds max {self.policy.max_slash_bps}bps"

    return True, "approved"
```

Every decision is logged where the owner can read it. The key is kept in the operating system's keychain, or in an encrypted file where there is none.

What a reviewer would say: amounts are floating-point numbers, and the 24-hour window is held in memory so a restart resets the daily cap. A negative or not-a-number amount used to pass; it is now refused before anything else is looked at.

## How it is tested [#how-it-is-tested]

When I compiled the contracts for this page, two of the three did not build: the reputation contract used a variable by the wrong name, and the identity tests compared a type that could not be compared. Of 18 tests written, 7 could run.

Since [pull request 3](https://github.com/Beach-Bum/agora-agent/pull/3) all three build and 24 contract tests pass: 13 on escrow, 6 on identity, 5 on reputation. The agent, which had no tests, has 37, on signing, message validation and the spending check.

## What it does not do [#what-it-does-not-do]

- **No trade completes end to end.** The seller commits to a placeholder hash, the function that announces a delivery is never called, and the path that creates an escrow does not go through the wallet's limits.
- **Only the five marketplace messages are signed.** Direct messages, topic messages and agent cards are still unauthenticated.
- **The contracts are models.** They hold balances in memory and take the caller's identity as an argument. Nothing is deployed, and the Python agent does not call them.
- **There is an operator in two places.** Disputes are settled by one fixed arbiter, and the client trusts whichever node it is pointed at.
- **A hosted model is the fallback.** With an OpenAI key set, the agent uses it when no local model answers.
- **It falls back to a stand-in.** When no Logos node can be reached, the blockchain client quietly switches to a mock so the rest keeps working. That is useful for development and would be dangerous anywhere real: a trade could appear to settle when nothing did.
- **No real value has moved through it.**
- **No test runs against a live node.** The agent's tests are unit tests.
- **Ten commits.** This is a prototype built for a submission, not a maintained system.

## More [#more]

<Cards>
  <Card title="Source on GitHub" href="https://github.com/Beach-Bum/agora-agent" />
  <Card title="Project notes on the weblog" href="https://nedkarlovich.com/projects/agora" />
</Cards>
