feat(base,app,learn,todo,train,meditate): agent accounts with tokens

ADR 0044's step 6a (D42, D43, D45): accounts for programs, such as AI
assistants, that an identified person makes from the Profile.

halkyon_base keeps them on the instance's register, which its members
ask: an agent is an account (agent_account: its owner, its name, its
public keys, set by itself once) with one token (agent_token: 32
random bytes, kept as their SHA-256 alone, shown once). agents.create,
mine, newToken, revoke, delete and setKeys serve its owner;
agentSignIn.signIn exchanges the token for an ordinary server-side
session of a day, with the scopes identified and agent, at most 60
sign-ins an hour from a network. Revoking a token or making a new one
ends the agent's sessions; a token unused for 90 days lapses in every
service's pruning. Up to 5 agents a person, where the operator didn't
switch them off (AGENTS=off; said on the privacy page and in
instance.basics). An agent makes no agents, creates or owns no shared
space, is invited and raised as a Viewer alone, is never handed a
space on, is named no operator and granted no assistants; each refusal
has its test. Deleting a person deletes their agents first; an agent's
public profile names whose agent it is.

In the apps, every Profile has an Agents card (halkyon_app's
AgentsSection): made with a name and a handle, its token shown once to
copy, a new token, the token taken back, deleted. Learn's Share sheet
marks an agent among the members and offers it no role above Viewer.

The migrations, the module's and each host's (Learn, Meditate, Todo,
Train), are additive alone: CREATE TABLE "agent_account" with a unique
index on "agentId" (one row an agent account) and one on "ownerId" (a
person's agents, and deleting them with the person), and CREATE TABLE
"agent_token" with unique indexes on "agentId" (one token an agent)
and "tokenHash" (the sign-in finds the token by its hash). No existing
table is touched, so the server before the deploy keeps working on the
migrated database.

Whats-New: Make agents in your Profile: accounts for programs such as AI assistants, which sign in with a token and see only what you share with them.
Whats-New-De: Leg in deinem Profil Agenten an: Konten für Programme wie KI-Assistenten, die sich mit einem Token anmelden und nur sehen, was du mit ihnen teilst.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Tizian 「ティツィアーン」 <raisondetredev@pm.me>
This commit is contained in:
Tizian 「ティツィアーン」 2026-11-11 19:55:27 +01:00
commit 7aee78bd87
Signed by: raisondetredev
GPG key ID: 07F6FCF405488B64
92 changed files with 113257 additions and 50 deletions

View file

@ -55,6 +55,12 @@ library;
export 'package:halkyon_keys/halkyon_keys.dart' show PublicKeys;
export 'l10n/halkyon_app_localizations.dart';
export 'src/agent/bloc/agents_cubit.dart';
export 'src/agent/data/agent_gateway.dart';
export 'src/agent/data/agent_repository.dart';
export 'src/agent/data/serverpod_agent_gateway.dart';
export 'src/agent/model/agent.dart';
export 'src/agent/widget/agents_section.dart';
export 'src/app/about.dart';
export 'src/app/app_frame.dart' show AppFrame, AppFrameScope, LookSettings;
export 'src/app/app_locale.dart';

View file

@ -531,5 +531,34 @@
"mobileDataEverything": "Alles synchronisieren",
"mobileDataBanner": "Mobile Daten · {count, plural, =0{Synchronisierung pausiert} =1{1 Änderung wartet} other{{count} Änderungen warten}}",
"mobileDataBannerWithoutFiles": "Ohne Dateien",
"mobileDataBannerNotNow": "Nicht jetzt"
"mobileDataBannerNotNow": "Nicht jetzt",
"agentsTitle": "Agenten",
"agentsIntro": "Ein Agent ist ein Konto von dir für ein Programm, etwa einen KI-Assistenten. Er meldet sich mit einem Token an, sieht nur, wozu du ihn einlädst, als Betrachter, und schlägt Änderungen vor, statt sie zu machen.",
"agentsNone": "Noch keine Agenten.",
"agentsMake": "Agent anlegen",
"agentsName": "Name",
"agentsMakeAction": "Anlegen",
"agentsTokenTitle": "Token für @{handle}",
"agentsTokenBody": "Gib diesen Token dem Programm, für das der Agent ist. Er wird nur jetzt angezeigt: Geht er verloren, erstelle einen neuen. 90 Tage unbenutzt, verfällt er.",
"agentsTokenCopy": "Token kopieren",
"agentsTokenCopied": "Token kopiert",
"agentsDone": "Fertig",
"agentsLastUsed": "@{handle} · angemeldet am {date}",
"agentsNeverUsed": "@{handle} · noch nie angemeldet",
"agentsNoToken": "@{handle} · kein Token",
"agentsNewToken": "Neuer Token",
"agentsRevoke": "Token zurücknehmen",
"agentsRevokeTitle": "Token von @{handle} zurücknehmen?",
"agentsRevokeMessage": "Er kann sich nicht mehr anmelden, und seine Sitzungen enden, bis du ihm einen neuen Token gibst.",
"agentsDelete": "Löschen",
"agentsDeleteTitle": "@{handle} löschen?",
"agentsDeleteMessage": "Sein Konto wird gelöscht und mit ihm seine Mitgliedschaften.",
"agentsActions": "Optionen für @{handle}",
"agentProblemAgentsOff": "Diese Instanz erlaubt keine Agenten.",
"agentProblemTooMany": "Du hast so viele Agenten, wie du darfst ({count}).",
"agentProblemNameTooLong": "Dieser Name ist zu lang.",
"agentProblemNotFound": "Diesen Agenten gibt es nicht mehr.",
"agentProblemFailed": "Die Instanz war nicht erreichbar. Versuch es noch einmal.",
"agentOf": "Agent von @{owner}",
"operatorIsAgent": "Ein Agent kann weder Admin sein noch Assistenten bekommen."
}

View file

@ -1609,5 +1609,44 @@
"mobileDataBannerWithoutFiles": "Without files",
"@mobileDataBannerWithoutFiles": {"description": "The banner's action syncing the rows alone, files waiting for Wi-Fi."},
"mobileDataBannerNotNow": "Not now",
"@mobileDataBannerNotNow": {"description": "The banner's action hiding it until another change waits."}
"@mobileDataBannerNotNow": {"description": "The banner's action hiding it until another change waits."},
"agentsTitle": "Agents",
"agentsIntro": "An agent is an account of yours for a program, such as an AI assistant. It signs in with a token, sees only what you invite it to, as a Viewer, and suggests changes rather than making them.",
"agentsNone": "No agents yet.",
"agentsMake": "Make an agent",
"agentsName": "Name",
"agentsMakeAction": "Make",
"agentsTokenTitle": "Token for @{handle}",
"@agentsTokenTitle": {"placeholders": {"handle": {"type": "String"}}},
"agentsTokenBody": "Give this token to the program the agent is for. It's shown only now: if it's lost, make a new one. Unused for 90 days, it lapses.",
"agentsTokenCopy": "Copy token",
"agentsTokenCopied": "Token copied",
"agentsDone": "Done",
"agentsLastUsed": "@{handle} · signed in {date}",
"@agentsLastUsed": {"placeholders": {"handle": {"type": "String"}, "date": {"type": "String"}}},
"agentsNeverUsed": "@{handle} · never signed in",
"@agentsNeverUsed": {"placeholders": {"handle": {"type": "String"}}},
"agentsNoToken": "@{handle} · no token",
"@agentsNoToken": {"placeholders": {"handle": {"type": "String"}}},
"agentsNewToken": "New token",
"agentsRevoke": "Take back token",
"agentsRevokeTitle": "Take back @{handle}'s token?",
"@agentsRevokeTitle": {"placeholders": {"handle": {"type": "String"}}},
"agentsRevokeMessage": "It signs in no more, and its sessions end, until you give it a new token.",
"agentsDelete": "Delete",
"agentsDeleteTitle": "Delete @{handle}?",
"@agentsDeleteTitle": {"placeholders": {"handle": {"type": "String"}}},
"agentsDeleteMessage": "Its account goes, and with it its memberships.",
"agentsActions": "Options for @{handle}",
"@agentsActions": {"placeholders": {"handle": {"type": "String"}}},
"agentProblemAgentsOff": "This instance doesn't allow agents.",
"agentProblemTooMany": "You have as many agents as you may ({count}).",
"@agentProblemTooMany": {"placeholders": {"count": {"type": "int"}}},
"agentProblemNameTooLong": "This name is too long.",
"agentProblemNotFound": "This agent is gone.",
"agentProblemFailed": "The instance couldn't be reached. Try again.",
"agentOf": "Agent of @{owner}",
"@agentOf": {"placeholders": {"owner": {"type": "String"}}},
"operatorIsAgent": "An agent can't be an operator or be granted assistants.",
"@operatorIsAgent": {"description": "Naming an agent an operator, or granting it an assistant, refused"}
}

View file

@ -3294,6 +3294,180 @@ abstract class HalkyonAppLocalizations {
/// In en, this message translates to:
/// **'Not now'**
String get mobileDataBannerNotNow;
/// No description provided for @agentsTitle.
///
/// In en, this message translates to:
/// **'Agents'**
String get agentsTitle;
/// No description provided for @agentsIntro.
///
/// In en, this message translates to:
/// **'An agent is an account of yours for a program, such as an AI assistant. It signs in with a token, sees only what you invite it to, as a Viewer, and suggests changes rather than making them.'**
String get agentsIntro;
/// No description provided for @agentsNone.
///
/// In en, this message translates to:
/// **'No agents yet.'**
String get agentsNone;
/// No description provided for @agentsMake.
///
/// In en, this message translates to:
/// **'Make an agent'**
String get agentsMake;
/// No description provided for @agentsName.
///
/// In en, this message translates to:
/// **'Name'**
String get agentsName;
/// No description provided for @agentsMakeAction.
///
/// In en, this message translates to:
/// **'Make'**
String get agentsMakeAction;
/// No description provided for @agentsTokenTitle.
///
/// In en, this message translates to:
/// **'Token for @{handle}'**
String agentsTokenTitle(String handle);
/// No description provided for @agentsTokenBody.
///
/// In en, this message translates to:
/// **'Give this token to the program the agent is for. It\'s shown only now: if it\'s lost, make a new one. Unused for 90 days, it lapses.'**
String get agentsTokenBody;
/// No description provided for @agentsTokenCopy.
///
/// In en, this message translates to:
/// **'Copy token'**
String get agentsTokenCopy;
/// No description provided for @agentsTokenCopied.
///
/// In en, this message translates to:
/// **'Token copied'**
String get agentsTokenCopied;
/// No description provided for @agentsDone.
///
/// In en, this message translates to:
/// **'Done'**
String get agentsDone;
/// No description provided for @agentsLastUsed.
///
/// In en, this message translates to:
/// **'@{handle} · signed in {date}'**
String agentsLastUsed(String handle, String date);
/// No description provided for @agentsNeverUsed.
///
/// In en, this message translates to:
/// **'@{handle} · never signed in'**
String agentsNeverUsed(String handle);
/// No description provided for @agentsNoToken.
///
/// In en, this message translates to:
/// **'@{handle} · no token'**
String agentsNoToken(String handle);
/// No description provided for @agentsNewToken.
///
/// In en, this message translates to:
/// **'New token'**
String get agentsNewToken;
/// No description provided for @agentsRevoke.
///
/// In en, this message translates to:
/// **'Take back token'**
String get agentsRevoke;
/// No description provided for @agentsRevokeTitle.
///
/// In en, this message translates to:
/// **'Take back @{handle}\'s token?'**
String agentsRevokeTitle(String handle);
/// No description provided for @agentsRevokeMessage.
///
/// In en, this message translates to:
/// **'It signs in no more, and its sessions end, until you give it a new token.'**
String get agentsRevokeMessage;
/// No description provided for @agentsDelete.
///
/// In en, this message translates to:
/// **'Delete'**
String get agentsDelete;
/// No description provided for @agentsDeleteTitle.
///
/// In en, this message translates to:
/// **'Delete @{handle}?'**
String agentsDeleteTitle(String handle);
/// No description provided for @agentsDeleteMessage.
///
/// In en, this message translates to:
/// **'Its account goes, and with it its memberships.'**
String get agentsDeleteMessage;
/// No description provided for @agentsActions.
///
/// In en, this message translates to:
/// **'Options for @{handle}'**
String agentsActions(String handle);
/// No description provided for @agentProblemAgentsOff.
///
/// In en, this message translates to:
/// **'This instance doesn\'t allow agents.'**
String get agentProblemAgentsOff;
/// No description provided for @agentProblemTooMany.
///
/// In en, this message translates to:
/// **'You have as many agents as you may ({count}).'**
String agentProblemTooMany(int count);
/// No description provided for @agentProblemNameTooLong.
///
/// In en, this message translates to:
/// **'This name is too long.'**
String get agentProblemNameTooLong;
/// No description provided for @agentProblemNotFound.
///
/// In en, this message translates to:
/// **'This agent is gone.'**
String get agentProblemNotFound;
/// No description provided for @agentProblemFailed.
///
/// In en, this message translates to:
/// **'The instance couldn\'t be reached. Try again.'**
String get agentProblemFailed;
/// No description provided for @agentOf.
///
/// In en, this message translates to:
/// **'Agent of @{owner}'**
String agentOf(String owner);
/// Naming an agent an operator, or granting it an assistant, refused
///
/// In en, this message translates to:
/// **'An agent can\'t be an operator or be granted assistants.'**
String get operatorIsAgent;
}
class _HalkyonAppLocalizationsDelegate

View file

@ -2069,4 +2069,115 @@ class HalkyonAppLocalizationsDe extends HalkyonAppLocalizations {
@override
String get mobileDataBannerNotNow => 'Nicht jetzt';
@override
String get agentsTitle => 'Agenten';
@override
String get agentsIntro =>
'Ein Agent ist ein Konto von dir für ein Programm, etwa einen KI-Assistenten. Er meldet sich mit einem Token an, sieht nur, wozu du ihn einlädst, als Betrachter, und schlägt Änderungen vor, statt sie zu machen.';
@override
String get agentsNone => 'Noch keine Agenten.';
@override
String get agentsMake => 'Agent anlegen';
@override
String get agentsName => 'Name';
@override
String get agentsMakeAction => 'Anlegen';
@override
String agentsTokenTitle(String handle) {
return 'Token für @$handle';
}
@override
String get agentsTokenBody =>
'Gib diesen Token dem Programm, für das der Agent ist. Er wird nur jetzt angezeigt: Geht er verloren, erstelle einen neuen. 90 Tage unbenutzt, verfällt er.';
@override
String get agentsTokenCopy => 'Token kopieren';
@override
String get agentsTokenCopied => 'Token kopiert';
@override
String get agentsDone => 'Fertig';
@override
String agentsLastUsed(String handle, String date) {
return '@$handle · angemeldet am $date';
}
@override
String agentsNeverUsed(String handle) {
return '@$handle · noch nie angemeldet';
}
@override
String agentsNoToken(String handle) {
return '@$handle · kein Token';
}
@override
String get agentsNewToken => 'Neuer Token';
@override
String get agentsRevoke => 'Token zurücknehmen';
@override
String agentsRevokeTitle(String handle) {
return 'Token von @$handle zurücknehmen?';
}
@override
String get agentsRevokeMessage =>
'Er kann sich nicht mehr anmelden, und seine Sitzungen enden, bis du ihm einen neuen Token gibst.';
@override
String get agentsDelete => 'Löschen';
@override
String agentsDeleteTitle(String handle) {
return '@$handle löschen?';
}
@override
String get agentsDeleteMessage =>
'Sein Konto wird gelöscht und mit ihm seine Mitgliedschaften.';
@override
String agentsActions(String handle) {
return 'Optionen für @$handle';
}
@override
String get agentProblemAgentsOff => 'Diese Instanz erlaubt keine Agenten.';
@override
String agentProblemTooMany(int count) {
return 'Du hast so viele Agenten, wie du darfst ($count).';
}
@override
String get agentProblemNameTooLong => 'Dieser Name ist zu lang.';
@override
String get agentProblemNotFound => 'Diesen Agenten gibt es nicht mehr.';
@override
String get agentProblemFailed =>
'Die Instanz war nicht erreichbar. Versuch es noch einmal.';
@override
String agentOf(String owner) {
return 'Agent von @$owner';
}
@override
String get operatorIsAgent =>
'Ein Agent kann weder Admin sein noch Assistenten bekommen.';
}

View file

@ -2037,6 +2037,117 @@ class HalkyonAppLocalizationsEn extends HalkyonAppLocalizations {
@override
String get mobileDataBannerNotNow => 'Not now';
@override
String get agentsTitle => 'Agents';
@override
String get agentsIntro =>
'An agent is an account of yours for a program, such as an AI assistant. It signs in with a token, sees only what you invite it to, as a Viewer, and suggests changes rather than making them.';
@override
String get agentsNone => 'No agents yet.';
@override
String get agentsMake => 'Make an agent';
@override
String get agentsName => 'Name';
@override
String get agentsMakeAction => 'Make';
@override
String agentsTokenTitle(String handle) {
return 'Token for @$handle';
}
@override
String get agentsTokenBody =>
'Give this token to the program the agent is for. It\'s shown only now: if it\'s lost, make a new one. Unused for 90 days, it lapses.';
@override
String get agentsTokenCopy => 'Copy token';
@override
String get agentsTokenCopied => 'Token copied';
@override
String get agentsDone => 'Done';
@override
String agentsLastUsed(String handle, String date) {
return '@$handle · signed in $date';
}
@override
String agentsNeverUsed(String handle) {
return '@$handle · never signed in';
}
@override
String agentsNoToken(String handle) {
return '@$handle · no token';
}
@override
String get agentsNewToken => 'New token';
@override
String get agentsRevoke => 'Take back token';
@override
String agentsRevokeTitle(String handle) {
return 'Take back @$handle\'s token?';
}
@override
String get agentsRevokeMessage =>
'It signs in no more, and its sessions end, until you give it a new token.';
@override
String get agentsDelete => 'Delete';
@override
String agentsDeleteTitle(String handle) {
return 'Delete @$handle?';
}
@override
String get agentsDeleteMessage =>
'Its account goes, and with it its memberships.';
@override
String agentsActions(String handle) {
return 'Options for @$handle';
}
@override
String get agentProblemAgentsOff => 'This instance doesn\'t allow agents.';
@override
String agentProblemTooMany(int count) {
return 'You have as many agents as you may ($count).';
}
@override
String get agentProblemNameTooLong => 'This name is too long.';
@override
String get agentProblemNotFound => 'This agent is gone.';
@override
String get agentProblemFailed =>
'The instance couldn\'t be reached. Try again.';
@override
String agentOf(String owner) {
return 'Agent of @$owner';
}
@override
String get operatorIsAgent =>
'An agent can\'t be an operator or be granted assistants.';
}
/// The translations for English, as used in the United Kingdom (`en_GB`).

View file

@ -0,0 +1,107 @@
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:halkyon_app/src/agent/data/agent_repository.dart';
import 'package:halkyon_app/src/agent/model/agent.dart';
/// The signed-in person's agents as the Profile shows them (Halkyon's ADR
/// 0044, D45): read as it opens, made, given new tokens, their tokens taken
/// back and deleted, each change read back from the instance.
class AgentsCubit(final AgentRepository _agents) extends Cubit<AgentsState> {
this : super(const AgentsState());
/// Reads whether the instance offers agents, and the person's.
Future<void> load() async {
try {
final offered = await _agents.offered();
final mine = await _agents.mine();
_emit(AgentsState(offered: offered, agents: mine));
} on AgentFailed catch (failed) {
_emit(state.copyWith(problem: failed.problem));
}
}
/// Makes an agent called [name] with [handle]; what was made, with its
/// token, or null where it was refused, the refusal in
/// [AgentsState.makeProblem], which the dialog making it shows.
Future<MadeAgent?> create({required String name, required String handle}) =>
_step(() => _agents.create(name: name, handle: handle), making: true);
/// Gives the agent [agent] a new token; null where it was refused.
Future<MadeAgent?> newToken(String agent) =>
_step(() => _agents.newToken(agent));
/// Takes the agent [agent]'s token back; whether it went.
Future<bool> revoke(String agent) async =>
await _step(() async {
await _agents.revoke(agent);
return true;
}) ??
false;
/// Deletes the agent [agent]; whether it went.
Future<bool> delete(String agent) async =>
await _step(() async {
await _agents.delete(agent);
return true;
}) ??
false;
/// Forgets why making an agent was refused, as its dialog closes.
void forgetMakeProblem() => _emit(state.copyWith());
Future<T?> _step<T>(Future<T> Function() step, {bool making = false}) async {
_emit(state.copyWith(busy: true));
try {
final done = await step();
final mine = await _agents.mine();
_emit(AgentsState(offered: state.offered, agents: mine));
return done;
} on AgentFailed catch (failed) {
_emit(
making
? state.copyWith(makeProblem: failed.problem)
: state.copyWith(problem: failed.problem),
);
return null;
}
}
void _emit(AgentsState next) {
if (!isClosed) {
emit(next);
}
}
}
/// Whether the instance [offered] agents (null until it said), the
/// person's [agents], whether a change is under way ([busy]) and what was
/// refused last: making an agent ([makeProblem], in its dialog), or
/// anything else ([problem], on the card).
final class const AgentsState({
final bool? offered,
final List<Agent> agents = const [],
final bool busy = false,
final AgentProblem? problem,
final AgentProblem? makeProblem,
}) with Equatable {
/// Whether the Profile shows agents: offered, or some made before the
/// operator switched them off.
bool get shown => (offered ?? false) || agents.isNotEmpty;
/// The same agents with [busy], [problem] and [makeProblem] as given: a
/// new step forgets the refusals before.
AgentsState copyWith({
bool busy = false,
AgentProblem? problem,
AgentProblem? makeProblem,
}) => AgentsState(
offered: offered,
agents: agents,
busy: busy,
problem: problem,
makeProblem: makeProblem,
);
@override
List<Object?> get props => [offered, agents, busy, problem, makeProblem];
}

View file

@ -0,0 +1,24 @@
import 'package:halkyon_app/src/agent/model/agent.dart';
/// The boundary to the signed-in person's agents on the instance
/// (Halkyon's ADR 0044, D6, D12, D45): failures are [AgentFailed]s. Tests
/// replace it with a fake.
abstract interface class AgentGateway() {
/// Whether people may make agents on the instance.
Future<bool> offered();
/// The person's agents, the first made first.
Future<List<Agent>> mine();
/// Makes an agent called [name] with [handle], and its token.
Future<MadeAgent> create({required String name, required String handle});
/// Gives the agent [agent] a new token, the one before ending.
Future<MadeAgent> newToken(String agent);
/// Takes the agent [agent]'s token back: it signs in no more.
Future<void> revoke(String agent);
/// Deletes the agent [agent].
Future<void> delete(String agent);
}

View file

@ -0,0 +1,32 @@
import 'package:halkyon_app/src/agent/data/agent_gateway.dart';
import 'package:halkyon_app/src/agent/model/agent.dart';
/// The signed-in person's agents (Halkyon's ADR 0044, D6, D45), as the
/// Profile lists, makes and takes them back: what the instance answers, as
/// [AgentFailed]s where it refuses.
class AgentRepository(final AgentGateway _gateway) {
/// Whether people may make agents on the instance.
Future<bool> offered() => _gateway.offered();
/// The person's agents, the first made first.
Future<List<Agent>> mine() => _gateway.mine();
/// Makes an agent called [name] with [handle] (without an `@` before it),
/// and its token, shown once.
Future<MadeAgent> create({required String name, required String handle}) {
final bare = handle.trim();
return _gateway.create(
name: name.trim(),
handle: bare.startsWith('@') ? bare.substring(1) : bare,
);
}
/// Gives the agent [agent] a new token, the one before ending.
Future<MadeAgent> newToken(String agent) => _gateway.newToken(agent);
/// Takes the agent [agent]'s token back.
Future<void> revoke(String agent) => _gateway.revoke(agent);
/// Deletes the agent [agent].
Future<void> delete(String agent) => _gateway.delete(agent);
}

View file

@ -0,0 +1,90 @@
import 'package:halkyon_app/src/agent/data/agent_gateway.dart';
import 'package:halkyon_app/src/agent/model/agent.dart';
import 'package:halkyon_app/src/handle/data/handle_refusals.dart';
import 'package:halkyon_app/src/handle/model/handle_problem.dart';
import 'package:halkyon_base_client/halkyon_base_client.dart' as protocol;
import 'package:serverpod_client/serverpod_client.dart';
/// [AgentGateway] on the module's endpoints of an app's client ([_base],
/// `client.modules.base`), as the device's person.
class ServerpodAgentGateway(final protocol.Caller _base)
implements AgentGateway {
@override
Future<bool> offered() =>
_call(() async => (await _base.instance.basics()).agents);
@override
Future<List<Agent>> mine() =>
_call(() async => [...(await _base.agents.mine()).map(_of)]);
@override
Future<MadeAgent> create({required String name, required String handle}) =>
_call(
() async =>
_made(await _base.agents.create(name: name, handle: handle)),
);
@override
Future<MadeAgent> newToken(String agent) => _call(
() async => _made(await _base.agents.newToken(agent: _idOf(agent))),
);
@override
Future<void> revoke(String agent) =>
_call(() => _base.agents.revoke(agent: _idOf(agent)));
@override
Future<void> delete(String agent) =>
_call(() => _base.agents.delete(agent: _idOf(agent)));
static MadeAgent _made(protocol.AgentMade made) =>
MadeAgent(agent: _of(made.agent), token: made.token);
static Agent _of(protocol.AgentInfo agent) => Agent(
id: agent.id.uuid,
name: agent.name,
handle: agent.handle,
createdAt: agent.createdAt,
lastUsedAt: agent.lastUsedAt,
hasToken: agent.hasToken,
hasKeys: agent.hasKeys,
);
static UuidValue _idOf(String agent) {
try {
return UuidValue.withValidation(agent);
} on FormatException {
throw const AgentFailed(AgentProblem.notFound);
}
}
}
/// [call], its refusals as [AgentFailed]s.
Future<T> _call<T>(Future<T> Function() call) async {
try {
return await call();
} on protocol.AgentRefusedException catch (refusal) {
throw AgentFailed(switch (refusal.reason) {
protocol.AgentRefusal.agentsOff => AgentProblem.agentsOff,
protocol.AgentRefusal.tooMany => AgentProblem.tooMany,
protocol.AgentRefusal.noSuchAgent => AgentProblem.notFound,
// None but an agent's or a lapsed token's own: not for the Profile.
protocol.AgentRefusal.notForAgents ||
protocol.AgentRefusal.notValid ||
protocol.AgentRefusal.keysSet ||
protocol.AgentRefusal.tooManyAttempts => AgentProblem.failed,
});
} on protocol.ProfileRefusedException catch (refusal) {
throw AgentFailed(switch (handleProblemOf(refusal.reason)) {
HandleProblem.invalid => AgentProblem.handleInvalid,
HandleProblem.reserved => AgentProblem.handleReserved,
HandleProblem.taken => AgentProblem.handleTaken,
HandleProblem.tooManyChecks => AgentProblem.tooManyHandleChecks,
// A name too long is the only other an agent's profile meets.
null => AgentProblem.nameTooLong,
});
} on Exception {
// No connection, the instance's own error, a timeout.
throw const AgentFailed(AgentProblem.failed);
}
}

View file

@ -0,0 +1,92 @@
import 'package:equatable/equatable.dart';
/// An agent of the signed-in person's (Halkyon's ADR 0044, D6, D45): an
/// account of its own that a program signs in to with a token, a Viewer
/// alone where it is invited, suggesting rather than changing.
final class const Agent({
/// Its account's ID, which the calls name it by.
required final String id,
/// What its owner called it.
required final String name,
/// Its handle, which it is invited by.
required final String handle,
/// When it was made.
required final DateTime createdAt,
/// When it last signed in with its token; null while never.
final DateTime? lastUsedAt,
/// Whether it has a token: taken back, none until a new one is made.
final bool hasToken = true,
/// Whether it set its public keys, as it does on its first start.
final bool hasKeys = false,
}) with Equatable {
@override
List<Object?> get props => [
id,
name,
handle,
createdAt,
lastUsedAt,
hasToken,
hasKeys,
];
}
/// An agent just made or given a new token, with the [token], which is
/// shown this once.
final class const MadeAgent({
required final Agent agent,
required final String token,
}) with Equatable {
@override
List<Object?> get props => [agent, token];
}
/// Why a call about agents failed.
enum AgentProblem() {
/// The instance's operator switched agents off.
agentsOff,
/// The person has as many agents as they may (5).
tooMany,
/// The handle can't be one: its letters, its length.
handleInvalid,
/// The handle is kept back for the instance.
handleReserved,
/// Someone has the handle.
handleTaken,
/// Too many handles were tried within an hour.
tooManyHandleChecks,
/// The name is too long.
nameTooLong,
/// No agent of the person's is that (any more).
notFound,
/// Anything else, such as no connection.
failed,
}
/// A call about agents failed, as [problem] says.
final class const AgentFailed(final AgentProblem problem)
with Equatable
implements Exception {
@override
List<Object?> get props => [problem];
@override
String toString() => 'AgentFailed(${problem.name})';
}
/// How many agents one person may have, as the instance allows.
const maxAgents = 5;

View file

@ -0,0 +1,351 @@
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:halkyon_app/l10n/halkyon_app_localizations.dart';
import 'package:halkyon_app/src/agent/bloc/agents_cubit.dart';
import 'package:halkyon_app/src/agent/model/agent.dart';
import 'package:halkyon_app/src/app/app_scope.dart';
import 'package:halkyon_app/src/handle/model/handle_problem.dart';
import 'package:halkyon_app/src/handle/widget/handle_field.dart';
import 'package:halkyon_app/src/password/widget/secret_clipboard.dart';
import 'package:halkyon_ui/halkyon_ui.dart';
import 'package:intl/intl.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:material_ui/material_ui.dart';
/// The Profile's card of the person's agents (Halkyon's ADR 0044, D6, D12,
/// D45): what an agent is, each of theirs with its handle and when it last
/// signed in, and making one, its token shown once; a new token, taking it
/// back and deleting from each one's menu. Nothing where the instance
/// offers no agents and the person has none. [clipboard] copies a token,
/// for a while.
class const AgentsSection({
final SecretClipboard clipboard = const PlatformSecretClipboard(),
super.key,
}) extends StatelessWidget {
@override
Widget build(BuildContext context) => BlocProvider(
create: (context) => AgentsCubit(AppScope.of(context).agents)..load(),
child: _AgentsCard(clipboard: clipboard),
);
}
class const _AgentsCard({required final SecretClipboard clipboard})
extends StatelessWidget {
@override
Widget build(BuildContext context) {
final l10n = HalkyonAppLocalizations.of(context);
final theme = Theme.of(context);
final state = context.watch<AgentsCubit>().state;
if (!state.shown) {
return const SizedBox.shrink();
}
return Padding(
padding: const EdgeInsets.only(top: 12),
child: SectionCard(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(l10n.agentsTitle, style: theme.textTheme.titleMedium),
const SizedBox(height: 4),
Text(l10n.agentsIntro),
const SizedBox(height: 8),
if (state.agents.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Text(
l10n.agentsNone,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
),
for (final agent in state.agents)
_AgentRow(agent: agent, clipboard: clipboard),
if (state.problem case final problem?)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
agentProblemText(l10n, problem),
style: TextStyle(color: theme.colorScheme.error),
),
),
if (state.offered ?? false) ...[
const SizedBox(height: 8),
Align(
alignment: AlignmentDirectional.centerStart,
child: OutlinedButton.icon(
onPressed: state.busy || state.agents.length >= maxAgents
? null
: () => unawaited(_make(context)),
icon: const Icon(LucideIcons.bot),
label: Text(l10n.agentsMake),
),
),
],
],
),
),
);
}
Future<void> _make(BuildContext context) async {
final cubit = context.read<AgentsCubit>();
final made = await showDialog<MadeAgent>(
context: context,
builder: (dialogContext) => BlocProvider.value(
value: cubit,
child: const _MakeAgentDialog(),
),
);
cubit.forgetMakeProblem();
if (made != null && context.mounted) {
await showAgentToken(context, made, clipboard: clipboard);
}
}
}
/// What [problem] means, in words.
String agentProblemText(HalkyonAppLocalizations l10n, AgentProblem problem) =>
switch (problem) {
AgentProblem.agentsOff => l10n.agentProblemAgentsOff,
AgentProblem.tooMany => l10n.agentProblemTooMany(maxAgents),
AgentProblem.handleInvalid => l10n.handleInvalid,
AgentProblem.handleReserved => l10n.handleReserved,
AgentProblem.handleTaken => l10n.handleTaken,
AgentProblem.tooManyHandleChecks => l10n.handleTooManyChecks,
AgentProblem.nameTooLong => l10n.agentProblemNameTooLong,
AgentProblem.notFound => l10n.agentProblemNotFound,
AgentProblem.failed => l10n.agentProblemFailed,
};
class const _AgentRow({
required final Agent agent,
required final SecretClipboard clipboard,
}) extends StatelessWidget {
@override
Widget build(BuildContext context) {
final l10n = HalkyonAppLocalizations.of(context);
final busy = context.select<AgentsCubit, bool>((cubit) => cubit.state.busy);
return ListTile(
contentPadding: EdgeInsets.zero,
leading: const Icon(LucideIcons.bot),
title: Text(agent.name, maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(
switch ((agent.hasToken, agent.lastUsedAt)) {
(false, _) => l10n.agentsNoToken(agent.handle),
(true, null) => l10n.agentsNeverUsed(agent.handle),
(true, final at?) => l10n.agentsLastUsed(
agent.handle,
DateFormat.yMMMd(l10n.localeName).format(at.toLocal()),
),
},
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
trailing: PopupMenuButton<_Action>(
icon: const Icon(LucideIcons.ellipsisVertical),
tooltip: l10n.agentsActions(agent.handle),
enabled: !busy,
onSelected: (action) => unawaited(_act(context, action)),
itemBuilder: (context) => [
PopupMenuItem(
value: _Action.newToken,
child: Text(l10n.agentsNewToken),
),
if (agent.hasToken)
PopupMenuItem(
value: _Action.revoke,
child: Text(l10n.agentsRevoke),
),
PopupMenuItem(value: _Action.delete, child: Text(l10n.agentsDelete)),
],
),
);
}
Future<void> _act(BuildContext context, _Action action) async {
final l10n = HalkyonAppLocalizations.of(context);
final cubit = context.read<AgentsCubit>();
switch (action) {
case _Action.newToken:
if (await cubit.newToken(agent.id) case final made?
when context.mounted) {
await showAgentToken(context, made, clipboard: clipboard);
}
case _Action.revoke:
if (await confirmDestructiveAction(
context,
title: l10n.agentsRevokeTitle(agent.handle),
message: l10n.agentsRevokeMessage,
confirmLabel: l10n.agentsRevoke,
)) {
await cubit.revoke(agent.id);
}
case _Action.delete:
if (await confirmDestructiveAction(
context,
title: l10n.agentsDeleteTitle(agent.handle),
message: l10n.agentsDeleteMessage,
confirmLabel: l10n.agentsDelete,
)) {
await cubit.delete(agent.id);
}
}
}
}
enum _Action() {
newToken,
revoke,
delete,
}
/// Asks for an agent's name and handle, and makes it; pops what was made.
class const _MakeAgentDialog() extends StatefulWidget {
@override
State<_MakeAgentDialog> createState() => _MakeAgentDialogState();
}
class _MakeAgentDialogState() extends State<_MakeAgentDialog> {
final _name = TextEditingController();
final _handle = TextEditingController();
@override
void dispose() {
_name.dispose();
_handle.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final l10n = HalkyonAppLocalizations.of(context);
final state = context.watch<AgentsCubit>().state;
final problem = state.makeProblem;
final handleProblem = switch (problem) {
AgentProblem.handleInvalid ||
AgentProblem.handleReserved ||
AgentProblem.handleTaken ||
AgentProblem.tooManyHandleChecks => problem,
_ => null,
};
return AlertDialog(
title: Text(l10n.agentsMake),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: _name,
autofocus: true,
maxLength: TextLimits.name,
buildCounter: nearLimitCounter,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
labelText: l10n.agentsName,
errorText: problem == AgentProblem.nameTooLong
? l10n.agentProblemNameTooLong
: null,
),
),
const SizedBox(height: 8),
HandleField(
controller: _handle,
enabled: !state.busy,
errorText: switch (handleProblem) {
final problem? => agentProblemText(l10n, problem),
null => null,
},
textInputAction: TextInputAction.done,
onSubmitted: (_) => unawaited(_make()),
),
if (problem != null &&
handleProblem == null &&
problem != AgentProblem.nameTooLong)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
agentProblemText(l10n, problem),
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(MaterialLocalizations.of(context).cancelButtonLabel),
),
ListenableBuilder(
listenable: _handle,
builder: (context, _) => FilledButton(
onPressed: state.busy || handleOf(_handle.text).isEmpty
? null
: () => unawaited(_make()),
child: state.busy
? const ButtonLoadingIndicator()
: Text(l10n.agentsMakeAction),
),
),
],
);
}
Future<void> _make() async {
final made = await context.read<AgentsCubit>().create(
name: _name.text,
handle: handleOf(_handle.text),
);
if (made != null && mounted) {
Navigator.of(context).pop(made);
}
}
}
/// Shows [made]'s token, this once, with a button copying it through
/// [clipboard].
Future<void> showAgentToken(
BuildContext context,
MadeAgent made, {
required SecretClipboard clipboard,
}) => showDialog<void>(
context: context,
builder: (context) {
final l10n = HalkyonAppLocalizations.of(context);
return AlertDialog(
title: Text(l10n.agentsTokenTitle(made.agent.handle)),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(l10n.agentsTokenBody),
const SizedBox(height: 12),
SelectableText(
made.token,
style: const TextStyle(fontFamily: 'monospace'),
),
],
),
actions: [
TextButton.icon(
onPressed: () async {
final messenger = ScaffoldMessenger.maybeOf(context);
await clipboard.copy(made.token);
messenger?.showSnackBar(
SnackBar(content: Text(l10n.agentsTokenCopied)),
);
},
icon: const Icon(LucideIcons.copy),
label: Text(l10n.agentsTokenCopy),
),
FilledButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(l10n.agentsDone),
),
],
);
},
);

View file

@ -1,4 +1,5 @@
import 'package:flutter/widgets.dart';
import 'package:halkyon_app/src/agent/data/agent_repository.dart';
import 'package:halkyon_app/src/assistant/data/assistant_repository.dart';
import 'package:halkyon_app/src/auth/data/auth_repository.dart';
import 'package:halkyon_app/src/auth/model/auth_status.dart';
@ -47,6 +48,11 @@ abstract interface class AppDependencies<P extends Disposable>()
/// ADR 0021, step 2).
AssistantRepository get assistants;
/// The signed-in person's agents (Halkyon's ADR 0044, D6, D45): accounts
/// of theirs that programs sign in to with a token, made and taken back
/// in the Profile.
AgentRepository get agents;
/// Granting assistants, with their limits and everyone's use, as the
/// instance's operators do (ADR 0021, points 2, 6 and 8); refused to
/// anyone else.

View file

@ -99,6 +99,7 @@ Future<T> operatorCall<T>(Future<T> Function() call) async {
protocol.OperatorRefusal.assistantNotSet =>
OperatorProblem.assistantNotSet,
protocol.OperatorRefusal.invalidLimit => OperatorProblem.invalidLimit,
protocol.OperatorRefusal.isAgent => OperatorProblem.isAgent,
});
} on ServerpodClientUnauthorized {
throw const OperatorFailed(OperatorProblem.notAllowed);

View file

@ -75,6 +75,10 @@ enum OperatorProblem() {
/// A limit below 0.
invalidLimit,
/// The account is an agent (Halkyon's ADR 0044, D45): never an operator,
/// and granted no assistant.
isAgent,
/// The signed-in person is no operator here (any more).
notAllowed,

View file

@ -266,6 +266,7 @@ String operatorProblemText(
OperatorProblem.assistantNotSet => l10n.operatorAssistantNotSet,
OperatorProblem.invalidLimit => l10n.operatorInvalidLimit,
OperatorProblem.notAllowed => l10n.operatorNotAllowed,
OperatorProblem.isAgent => l10n.operatorIsAgent,
OperatorProblem.failed || null => l10n.operatorFailed,
};

View file

@ -1,5 +1,6 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:halkyon_app/l10n/halkyon_app_localizations.dart';
import 'package:halkyon_app/src/agent/widget/agents_section.dart';
import 'package:halkyon_app/src/app/app_scope.dart';
import 'package:halkyon_app/src/auth/bloc/sign_in_ways_cubit.dart';
import 'package:halkyon_app/src/password/widget/account_security_section.dart';
@ -100,6 +101,9 @@ class const _Mine({required final List<Widget> sections})
],
const SizedBox(height: 12),
const SectionCard(child: PublicProfileSection()),
// The person's agents (Halkyon's ADR 0044, D45), where the
// instance offers them: a card of its own, or nothing.
const AgentsSection(),
],
),
),

View file

@ -143,6 +143,7 @@ class ServerpodSharedSpaceGateway(final protocol.Caller _base)
protocol.SharedSpaceRefusal.lastMember => SpaceRefusal.lastMember,
protocol.SharedSpaceRefusal.handleNeeded => SpaceRefusal.handleNeeded,
protocol.SharedSpaceRefusal.otherAddress => SpaceRefusal.otherAddress,
protocol.SharedSpaceRefusal.agentViewer => SpaceRefusal.agentViewer,
});
} on protocol.SharedSpaceNotFoundException {
throw const SpaceRefused(SpaceRefusal.notFound);
@ -176,6 +177,7 @@ class ServerpodSharedSpaceGateway(final protocol.Caller _base)
invited: member.invited,
you: member.you,
byEmail: member.byEmail,
agent: member.agent,
);
static SpaceRole _role(protocol.SharedSpaceRole role) => switch (role) {

View file

@ -89,6 +89,9 @@ final class const SpaceMember({
/// Whether this is an invitation mailed to an address (D38), which
/// members never see: neither handle nor name.
final bool byEmail = false,
/// Whether this is an agent's account (D44), a Viewer always.
final bool agent = false,
});
/// Why a call about a shared space was refused; nothing changed.
@ -139,6 +142,9 @@ enum SpaceRefusal() {
/// The mailed code is no longer valid: used, too many tries, too old.
codeExpired,
/// An agent is a Viewer, never more (ADR 0044, D44).
agentViewer,
/// No such space the person is in, or no such member in it; for a link,
/// one that holds no more.
notFound,

View file

@ -0,0 +1,109 @@
import 'package:clock/clock.dart';
import 'package:halkyon_app/src/agent/data/agent_gateway.dart';
import 'package:halkyon_app/src/agent/model/agent.dart';
/// An [AgentGateway] without a server, as the instance keeps agents
/// (Halkyon's ADR 0044, D45): up to [maxAgents], each handle once (the
/// [taken] ones someone else's), tokens `TOKEN-n`.
class FakeAgentGateway() implements AgentGateway {
/// Whether the operator offers agents.
bool isOffered = true;
/// The handles someone else has.
final taken = <String>{};
/// The agents, the first made first.
final agents = <Agent>[];
/// Thrown by every call while set: no connection.
bool unreachable = false;
var _tokens = 0;
void _reach() {
if (unreachable) {
throw const AgentFailed(AgentProblem.failed);
}
}
@override
Future<bool> offered() async {
_reach();
return isOffered;
}
@override
Future<List<Agent>> mine() async {
_reach();
return [...agents];
}
@override
Future<MadeAgent> create({
required String name,
required String handle,
}) async {
_reach();
if (!isOffered) {
throw const AgentFailed(AgentProblem.agentsOff);
}
if (agents.length >= maxAgents) {
throw const AgentFailed(AgentProblem.tooMany);
}
if (!RegExp(r'^[A-Za-z0-9_]{1,30}$').hasMatch(handle)) {
throw const AgentFailed(AgentProblem.handleInvalid);
}
final key = handle.toLowerCase();
if (taken.contains(key) ||
agents.any((agent) => agent.handle.toLowerCase() == key)) {
throw const AgentFailed(AgentProblem.handleTaken);
}
final agent = Agent(
id: 'agent-${agents.length + 1}',
name: name.isEmpty ? handle : name,
handle: handle,
createdAt: clock.now().toUtc(),
);
agents.add(agent);
return MadeAgent(agent: agent, token: _newToken());
}
@override
Future<MadeAgent> newToken(String agent) async {
final found = _found(agent);
final renewed = Agent(
id: found.id,
name: found.name,
handle: found.handle,
createdAt: found.createdAt,
hasKeys: found.hasKeys,
);
agents[agents.indexOf(found)] = renewed;
return MadeAgent(agent: renewed, token: _newToken());
}
@override
Future<void> revoke(String agent) async {
final found = _found(agent);
agents[agents.indexOf(found)] = Agent(
id: found.id,
name: found.name,
handle: found.handle,
createdAt: found.createdAt,
lastUsedAt: found.lastUsedAt,
hasToken: false,
hasKeys: found.hasKeys,
);
}
@override
Future<void> delete(String agent) async => agents.remove(_found(agent));
Agent _found(String agent) {
_reach();
return agents.where((each) => each.id == agent).firstOrNull ??
(throw const AgentFailed(AgentProblem.notFound));
}
String _newToken() => 'TOKEN-${++_tokens}';
}

Some files were not shown because too many files have changed in this diff Show more