Partager un espace entre agents
Ce projet fait travailler trois agents sur un espace partagé. alice crée l’espace et commence une tâche. carol reçoit un jeton de capacité en lecture seule. alice passe la tâche à bob : bob accepte la passation, lit sur place les notes, les messages et les épingles d’alice, écrit son résultat et termine la passation, ce qui révoque son jeton. À chaque étape, le programme affiche ce que chaque agent peut et ne peut pas faire. Utilisez-le quand plusieurs agents doivent partager un contexte sans tout partager.
Prérequis
- Erlang/OTP 26 ou plus récent (cette exécution a utilisé OTP 29) et rebar3.
- Un compilateur C et CMake pour les dépendances natives (la première compilation prend quelques minutes).
Exécuter
./run.sh
run.sh compile le projet, supprime ./data, puis exécute
agents_handoff:main/0 une fois.
Ce que montre l’exemple
barrel_caps:grant/2émet un jeton pour un espace avec des droits donnés ;barrel_caps:verify/3répondokou une raison :forbidden,wrong_space,invalid_token,revoked.barrel_handoff:create/2émet la passation sous forme de jeton (lecture et écriture par défaut, jamais admin).accept/2ne fonctionne qu’une fois : une seconde acceptation reçoitalready_accepted.- L’agent qui accepte lit sur place la session de l’émetteur et reçoit sa propre session, qui pointe vers la passation.
barrel_handoff:complete/2révoque le jeton de la passation ;barrel_caps:revoke/1révoque celui de carol.
Notes
- Dans le processus, les jetons sont indicatifs :
barrel_spaces:open_space/1et les fonctions debarrel_sessionne prennent pas de jeton, votre code appelle doncbarrel_caps:verify/3avant d’agir, comme le faitwrite_with/4ici.barrel_servervérifie les jetons à chaque requête REST et MCP. accept,completeetchainne vérifient que le droitreaddu jeton de passation.- Le chiffrement par espace est la frontière d’isolation au sein d’un nœud ; voir le guide des espaces.
Sortie attendue
Un bloc par agent, avec des lignes can et cannot. La sortie d’une
exécution réelle se trouve dans expected.txt ; les identifiants
d’espace et de passation changent à chaque exécution.
Télécharger Le dossier sur GitHub, avec tous les fichiers ci-dessous.
Code source
%% Two agents share a space: alice owns it, carol gets a read
%% token, bob takes the work over through a handoff.
-module(agents_handoff).
-export([main/0]).
main() ->
try run() of
ok -> halt(0)
catch C:R:S ->
io:format(standard_error, "~p:~p~n~p~n", [C, R, S]),
halt(1)
end.
run() ->
{ok, _} = application:ensure_all_started(barrel_spaces),
%% alice creates the space and starts the work.
{ok, #{id := SpaceId, db := Db} = Space} =
barrel_spaces:create_space(
#{label => <<"joint research">>, owner => <<"alice">>,
vectordb => none}),
io:format("alice created space ~s~n", [SpaceId]),
{ok, _} = barrel:put_doc(Db, #{<<"id">> => <<"notes">>,
<<"text">> => <<"draft v1">>}),
{ok, Sid} = barrel_session:create(
Space, #{agent => <<"alice">>, ttl => 1800}),
{ok, _} = barrel_session:add_message(
Space, Sid, #{role => <<"user">>,
content => <<"draft is half done">>}),
{ok, _} = barrel_session:pin_context(
Space, Sid, #{content => <<"deadline friday">>}),
%% carol gets a read token.
{ok, ReadTok, _} = barrel_caps:grant(
SpaceId, #{rights => [read], subject => <<"carol">>}),
io:format("~ncarol holds a read token~n"),
can("read the space", barrel_caps:verify(ReadTok, SpaceId, read)),
can("use it on another space",
barrel_caps:verify(ReadTok, <<"sp_other">>, read)),
can("use a tampered token",
barrel_caps:verify(<<ReadTok/binary, "x">>, SpaceId, read)),
can("write notes",
write_with(ReadTok, Space, <<"carol">>, <<"carol was here">>)),
%% alice hands the task to bob: the token is the handoff.
{ok, #{token := HTok}} = barrel_handoff:create(Space, #{
task_name => <<"finish the draft">>,
from_agent => <<"alice">>, to_agent => <<"bob">>,
from_session => Sid,
pending => [<<"polish conclusion">>]}),
io:format("~nalice handed off \"finish the draft\" to bob~n"),
{ok, [Pending]} = barrel_handoff:list(
#{to_agent => <<"bob">>, status => <<"pending">>}),
io:format("bob's pending handoffs: ~s~n",
[maps:get(<<"task_name">>, Pending)]),
can("write with the handoff token",
barrel_caps:verify(HTok, SpaceId, write)),
can("administer the space",
barrel_caps:verify(HTok, SpaceId, admin)),
%% bob accepts: he gets the space and a session of his own.
{ok, #{handoff := H, space := BobSpace, session := BobSid}} =
barrel_handoff:accept(HTok, #{agent => <<"bob">>}),
io:format("~nbob accepted: ~s by ~s~n",
[maps:get(<<"status">>, H),
maps:get(<<"accepted_by">>, H)]),
can("accept the same handoff again (mallory)",
barrel_handoff:accept(HTok, #{agent => <<"mallory">>})),
%% bob reads alice's context in place.
{ok, Notes} = barrel:get_doc(maps:get(db, BobSpace), <<"notes">>),
io:format("bob reads notes: ~s~n", [maps:get(<<"text">>, Notes)]),
{ok, Msgs} = barrel_session:get_messages(BobSpace, Sid),
io:format("bob reads alice's messages: ~p~n",
[[maps:get(<<"content">>, M) || M <- Msgs]]),
{ok, Pins} = barrel_session:list_pinned(BobSpace, Sid),
io:format("bob reads alice's pins: ~p~n",
[[maps:get(<<"content">>, P) || P <- Pins]]),
{ok, BobSession} = barrel_session:get(BobSpace, BobSid),
io:format("bob's session points at handoff: ~s~n",
[maps:get(<<"handoff_id">>,
maps:get(<<"data">>, BobSession))]),
can("write notes",
write_with(HTok, BobSpace, <<"bob">>, <<"draft v2">>)),
%% bob completes: the token is revoked.
{ok, Done} = barrel_handoff:complete(
HTok, #{result => <<"draft v2 ready">>}),
io:format("~nbob completed: ~s, result ~s~n",
[maps:get(<<"status">>, Done),
maps:get(<<"result">>, Done)]),
can("use the handoff token after completion",
barrel_caps:verify(HTok, SpaceId, read)),
%% alice revokes carol.
ok = barrel_caps:revoke(ReadTok),
io:format("~nalice revoked carol's token~n"),
can("read the space (carol)",
barrel_caps:verify(ReadTok, SpaceId, read)),
{ok, Final} = barrel:get_doc(Db, <<"notes">>),
io:format("~nnotes now: ~s (~s)~n",
[maps:get(<<"text">>, Final),
maps:get(<<"author">>, Final)]),
ok = barrel_spaces:close_space(SpaceId),
ok.
%% Tokens are checked by the code that holds them: in-process, the
%% Erlang API takes no token, so verify before acting. barrel_server
%% does this for every REST and MCP request.
write_with(Token, #{id := SpaceId, db := Db}, Who, Text) ->
case barrel_caps:verify(Token, SpaceId, write) of
{ok, _Grant} ->
{ok, Cur} = barrel:get_doc(Db, <<"notes">>),
{ok, _} = barrel:put_doc(Db, Cur#{<<"text">> => Text,
<<"author">> => Who}),
ok;
{error, _} = Err ->
Err
end.
can(What, ok) -> io:format(" can ~s~n", [What]);
can(What, {ok, _}) -> io:format(" can ~s~n", [What]);
can(What, {error, Reason}) ->
io:format(" cannot ~s: ~p~n", [What, Reason]). {erl_opts, [debug_info]}.
{deps, [{barrel, "~> 1.12"},
{barrel_spaces, "~> 1.3"}]}. #!/bin/sh
# Build, then run main/0 once on a fresh data directory.
set -e
cd "$(dirname "$0")"
rebar3 compile >&2
rm -rf data
exec erl -noshell -config config/sys \
-pa _build/default/lib/*/ebin _build/default/checkouts/*/ebin \
-eval 'agents_handoff:main()' Sortie attendue
Le fichier expected.txt de l’exemple, issu d’une exécution réelle. Les révisions, identifiants, jetons et horodatages changent à chaque exécution ; scripts/verify-examples.sh les masque avant de comparer.
alice created space sp_rhcq5uxrts6igoq4
carol holds a read token
can read the space
cannot use it on another space: wrong_space
cannot use a tampered token: invalid_token
cannot write notes: forbidden
alice handed off "finish the draft" to bob
bob's pending handoffs: finish the draft
can write with the handoff token
cannot administer the space: forbidden
bob accepted: accepted by bob
cannot accept the same handoff again (mallory): already_accepted
bob reads notes: draft v1
bob reads alice's messages: [<<"draft is half done">>]
bob reads alice's pins: [<<"deadline friday">>]
bob's session points at handoff: ho_26p5x345g6o2f64j
can write notes
bob completed: completed, result draft v2 ready
cannot use the handoff token after completion: revoked
alice revoked carol's token
cannot read the space (carol): revoked
notes now: draft v2 (bob)