# Accept a sub-agent

An agent hands a sub-agent part of its approval, never more, and it ends when the person withdraws the first.

| | |
|---|---|
| Level | 1: A person approves with a passkey. |
| Class | `read`: Nothing changes. The approval can be reused until it ends or the person withdraws it. |

## What the test proves

- the sub-agent reads the one note it was given, for the same person; nobody is asked
- every note is out of its reach, and more than the agent has cannot be handed on
- the chain works with the sub-agent's key only
- the person withdraws the agent's approval: the sub-agent's ends with it

## Python

```python
routes.append(route("GET", "/notes/{id}/summary", "notes:read", level=1, resource="note:{id}",
                    summary="Summarise one note"))


@app.get("/notes/<note_id>/summary")
def summarise(note_id):
    # An agent may hand a sub-agent part of its approval: the SDK checks the chain, and human_id is the same.
    note = notes.get(g.allowedby.human_id, note_id)
    if not note:
        return {"error": "no such note"}, 404
    return {"words": len(note["text"].split()), "delegated": len(g.allowedby.chain) > 1}
```

## JavaScript

```js
routes.push(route("GET", "/notes/{id}/summary", "notes:read", {
  level: 1, resource: "note:{id}", summary: "Summarise one note",
}));

api.get("/notes/:id/summary", (req, res) => {
  // An agent may hand a sub-agent part of its approval: the SDK checks the chain, and humanId is the same.
  const person = req.allowedby.humanId;
  if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by
  const note = notes.get(person, req.params.id);
  if (!note) return res.status(404).json({ error: "no such note" });
  res.json({ words: note.text.split(/\s+/).length, delegated: req.allowedby.chain.length > 1 });
});
```

## Go

```go
routes = append(routes, allowedby.Route{Method: "GET", Path: "/notes/{id}/summary", Capability: "notes:read",
	Class: allowedby.Read, Level: 1, Resource: "note:{id}", Summary: "Summarise one note"})

mux.HandleFunc("GET /notes/{id}/summary", func(w http.ResponseWriter, r *http.Request) {
	// An agent may hand a sub-agent part of its approval: the SDK checks the chain, and the person is the same.
	who, _ := allowedby.ContextFrom(r.Context())
	me, ok := who.Human() // false at level 0: an agent calls, with no person to keep data for
	if !ok {
		writeJSON(w, http.StatusForbidden, map[string]string{"error": "no person at level 0"})
		return
	}
	note, found := notes.Get(me, r.PathValue("id"))
	if !found {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": "no such note"})
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{
		"words": len(strings.Fields(note.Text)), "delegated": len(who.Chain) > 1})
})
```

## Java

```java
@Bean
AllowedByCustomizer delegate() {
    return aby -> aby.route(Route.get("/notes/{id}/summary").capability("notes:read").level(1)
            .resource("note:{id}").summary("Summarise one note"));
}

@GetMapping("/notes/{id}/summary")
ResponseEntity<Map<String, Object>> summarise(@AllowedByContext Context ctx, @PathVariable String id) {
    String person = ctx.getHumanId();
    if (person == null) { // level 0: no person, and never a key
        throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0");
    }
    // An agent may hand a sub-agent part of its approval: the SDK checks the chain, and getHumanId is the same.
    return notes.get(person, id)
            .map(note -> ResponseEntity.ok(Map.<String, Object>of("words", note.text().split("\\s+").length,
                    "delegated", ctx.getChain().size() > 1)))
            .orElse(ResponseEntity.status(404).body(Map.of("error", "no such note")));
}
```

## C#

```dotnet
routes.Add(Route("GET", "/notes/{id}/summary", "notes:read", level: 1, resource: "note:{id}",
    summary: "Summarise one note"));

app.MapGet("/notes/{id}/summary", (string id, AllowedByContext ctx) =>
{
    // An agent may hand a sub-agent part of its approval: the SDK checks the chain, and HumanId is the same.
    if (notes.Get(Person(ctx), id) is not { } note)
    {
        return Results.Json(new { error = "no such note" }, statusCode: 404);
    }
    var words = note.Text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Length;
    return Results.Json(new { words, delegated = ctx.Chain.Count > 1 });
});
```

## PHP

```php
$routes[] = route('GET', '/notes/{id}/summary', 'notes:read', level: 1, resource: 'note:{id}',
    summary: 'Summarise one note');

$app->get('/notes/{id}/summary', function (Request $request, Response $response, array $args) use ($json, $notes) {
    // An agent may hand a sub-agent part of its approval: the SDK checks the chain, and humanId is the same.
    $context = $request->getAttribute('allowedby.context');
    $note = $notes->get($context->humanId ?? throw new LogicException('no person at level 0'), $args['id']);
    if (null === $note) {
        return $json($response, ['error' => 'no such note'], 404);
    }

    $words = count(preg_split('/\s+/u', $note['text']));

    return $json($response, ['words' => $words, 'delegated' => count($context->chain) > 1]);
});
```

## Ruby

```ruby
ROUTES << AllowedBy.route(
  "GET", "/notes/{id}/summary", "notes:read",
  level: 1, resource: "note:{id}", summary: "Summarise one note"
)

get "/notes/:id/summary" do
  # An agent may hand a sub-agent part of its approval: the SDK checks the chain, and human_id is the same.
  context = env["allowedby.context"]
  person = context.human_id or halt 403, { error: "no person: this route needs one" }.to_json
  note = notes.get(person, params["id"])
  halt 404, { error: "no such note" }.to_json unless note
  { words: note[:text].split.length, delegated: context.chain.length > 1 }.to_json
end
```

## Rust

```rust
let aby = aby.route(
    Route::get("/notes/{id}/summary")
        .capability("notes:read")
        .level(1)
        .resource("note:{id}")
        .summary("Summarise one note"),
);
let app = app.route("/notes/{id}/summary", get(summarise));

async fn summarise(
    ctx: AllowedByContext,
    State(notes): State<Notes>,
    Path(id): Path<String>,
) -> Result<Json<Value>, Refusal> {
    // An agent may hand a sub-agent part of its approval: the SDK checks the chain, and human_id is the same.
    match notes.get(&ctx.human_id, &id) {
        Some(note) => {
            let words = note.text.split_whitespace().count();
            Ok(Json(json!({"words": words, "delegated": ctx.chain.len() > 1})))
        }
        None => Err((StatusCode::NOT_FOUND, Json(json!({"error": "no such note"})))),
    }
}
```
