Skip to content

Commit 7cda820

Browse files
ARTclaude
andcommitted
agents2: native identity list is the agent list; one-shot create; background delete cleanup
- Native identity rows carry type and name; localStorage holds optional settings by pubkey, defaulting to the type's defaults. - One app_agent_create command replaces prepare/authorize/commit and the pending list. - Keys are cached in native memory after first read, so publishing no longer races the credential store's try_lock. - Delete removes the key at once and marks the row deleted; leaving channels and archiving run whenever that community is open, then forget drops it. An unknown archive state never counts as "no profile". - The app owns kind 0: plugins can no longer publish it; native publishes {name, bot} when the name differs from the last accepted profile, newer than the last, one at a time. - Timers are checked when a run starts, after waiting events, so each has at most one occurrence pending and removed/expired timers never fire. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: ART <ea39c1c8acf57180161ef4ba4ed68abf8589f5291956b909a5aa991fc66664ca@buzz.block.builderlab.xyz>
1 parent df94680 commit 7cda820

19 files changed

Lines changed: 818 additions & 665 deletions

File tree

‎crates/agent-controller/src/app_agent.rs‎

Lines changed: 115 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
//! Identities for agents the app runs through a plugin (Agents2). They are not
22
//! harness agents: there is no process, harness setting or controller record.
33
//! Native keeps each key and its owner attestation and signs only bounded kinds.
4+
//! The saved identities are the agent list: each row names its type and name.
45
use crate::config::{agent_id, canonical_key, canonical_relay};
56
use crate::secret::validate_attestation;
67
use crate::{Credentials, Result, Secret};
78
use serde::{Deserialize, Serialize};
89
use std::path::PathBuf;
910

10-
/// What a plugin agent may publish: its profile (0), a deletion (5), a reaction
11-
/// (7), a message (9) or an edit of its own message (40003).
12-
const KINDS: [u16; 5] = [0, 5, 7, 9, 40003];
11+
/// What a plugin agent may publish: a deletion (5), a reaction (7), a message
12+
/// (9) or an edit of its own message (40003). Its profile (0) is the app's.
13+
const KINDS: [u16; 4] = [5, 7, 9, 40003];
1314

1415
/// One saved identity. The key itself stays in the OS credential store.
1516
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -21,6 +22,25 @@ pub struct AppAgent {
2122
pub owner: String,
2223
/// The owner's NIP-OA `auth` tag as a JSON array string.
2324
pub auth: String,
25+
/// The agent type's key, `pluginId/typeId`, fixed at create. Rows saved
26+
/// before it was recorded read as an unavailable type with no name.
27+
#[serde(rename = "type", default)]
28+
pub agent_type: String,
29+
#[serde(default)]
30+
pub name: String,
31+
/// The last profile its community accepted.
32+
#[serde(default, skip_serializing_if = "Option::is_none")]
33+
pub profile: Option<Published>,
34+
/// Its key is gone. The row stays until its community confirms it left its
35+
/// channels and was archived, which the owner signs, not the agent.
36+
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
37+
pub deleted: bool,
38+
}
39+
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
40+
#[serde(rename_all = "camelCase", deny_unknown_fields)]
41+
pub struct Published {
42+
pub name: String,
43+
pub created_at: u64,
2444
}
2545
impl AppAgent {
2646
fn credential_id(&self) -> String {
@@ -41,15 +61,10 @@ impl AppAgent {
4161
key: &Secret,
4262
kind: u16,
4363
content: String,
44-
mut tags: Vec<Vec<String>>,
64+
tags: Vec<Vec<String>>,
4565
) -> Result<serde_json::Value> {
46-
if key.pubkey() != self.pubkey {
47-
return Err("Agent identity changed".into());
48-
}
4966
if !KINDS.contains(&kind) {
50-
return Err(
51-
"Agents can sign profiles, messages, edits, reactions and deletions only".into(),
52-
);
67+
return Err("Agents can sign messages, edits, reactions and deletions only".into());
5368
}
5469
if content.len() > 64 * 1024
5570
|| tags.len() > 256
@@ -59,11 +74,31 @@ impl AppAgent {
5974
{
6075
return Err("Agent event is too large".into());
6176
}
77+
let tags = self.attested(key, tags)?;
78+
key.signed(kind, content, tags)
79+
}
80+
/// Its profile as this row describes it, replacing the last one accepted.
81+
/// No other writer exists: only this device holds the key.
82+
pub fn profile_event(&self, key: &Secret) -> Result<serde_json::Value> {
83+
valid_name(&self.name)?;
84+
let content = serde_json::json!({ "name": self.name, "bot": true }).to_string();
85+
let tags = self.attested(key, vec![])?;
86+
key.sign_event_after(
87+
0,
88+
content,
89+
tags,
90+
self.profile.as_ref().map(|p| p.created_at),
91+
)
92+
}
93+
fn attested(&self, key: &Secret, mut tags: Vec<Vec<String>>) -> Result<Vec<Vec<String>>> {
94+
if key.pubkey() != self.pubkey {
95+
return Err("Agent identity changed".into());
96+
}
6297
let auth: Vec<String> =
6398
serde_json::from_str(&self.auth).map_err(|_| "Invalid owner authorization")?;
6499
tags.retain(|tag| tag.first().map(String::as_str) != Some("auth"));
65100
tags.push(auth);
66-
key.signed(kind, content, tags)
101+
Ok(tags)
67102
}
68103
/// NIP-98 authorization for posting `body` to this agent's community.
69104
pub fn http_auth(&self, key: &Secret, body: &[u8]) -> Result<serde_json::Value> {
@@ -79,6 +114,8 @@ pub struct NewAppAgent {
79114
key: Secret,
80115
relay: String,
81116
owner: String,
117+
agent_type: String,
118+
name: String,
82119
}
83120
impl NewAppAgent {
84121
pub fn pubkey(&self) -> &str {
@@ -100,6 +137,7 @@ impl AppAgents {
100137
pub fn open(path: PathBuf) -> Self {
101138
Self { path }
102139
}
140+
/// Every row, deleted ones included.
103141
pub fn list(&self) -> Result<Vec<AppAgent>> {
104142
match std::fs::read(&self.path) {
105143
Ok(bytes) => serde_json::from_slice(&bytes)
@@ -108,10 +146,11 @@ impl AppAgents {
108146
Err(_) => Err("Could not read saved agent identities".into()),
109147
}
110148
}
149+
/// An agent that still has its key.
111150
pub fn get(&self, pubkey: &str) -> Result<AppAgent> {
112151
self.list()?
113152
.into_iter()
114-
.find(|agent| agent.pubkey == pubkey)
153+
.find(|agent| agent.pubkey == pubkey && !agent.deleted)
115154
.ok_or_else(|| "No such agent on this device".into())
116155
}
117156
/// Runs `change` on the saved list while holding the cross-process lock, and
@@ -142,26 +181,48 @@ impl AppAgents {
142181
std::fs::write(&temp, bytes).map_err(|_| "Could not save agent identities")?;
143182
std::fs::rename(&temp, &self.path).map_err(|_| "Could not save agent identities".into())
144183
}
145-
pub fn prepare(destination: &str, owner: &str) -> Result<NewAppAgent> {
184+
/// Changes one agent that still has its key.
185+
fn edit(&self, pubkey: &str, change: impl FnOnce(&mut AppAgent)) -> Result<()> {
186+
self.update(|agents| {
187+
let agent = agents
188+
.iter_mut()
189+
.find(|agent| agent.pubkey == pubkey && !agent.deleted)
190+
.ok_or("No such agent on this device")?;
191+
change(agent);
192+
Ok(())
193+
})
194+
}
195+
pub fn prepare(
196+
destination: &str,
197+
owner: &str,
198+
agent_type: &str,
199+
name: &str,
200+
) -> Result<NewAppAgent> {
146201
if !canonical_key(owner) {
147202
return Err("Choose a signed-in owner".into());
148203
}
204+
if agent_type.is_empty() || agent_type.len() > 256 {
205+
return Err("Choose an agent type".into());
206+
}
149207
Ok(NewAppAgent {
150208
relay: canonical_relay(destination)?,
151209
key: Secret::generate()?,
152210
owner: owner.into(),
211+
agent_type: agent_type.into(),
212+
name: valid_name(name)?,
153213
})
154214
}
155215
/// Saves the identity, then the key, so a saved key always has an identity to
156216
/// delete it by. If the key cannot be saved, the identity is withdrawn once
157217
/// its key is known to be gone; otherwise it stays for `remove` to retry.
158-
/// An attestation for another key or owner is refused.
218+
/// An attestation for another key or owner is refused. Returns the key too,
219+
/// so its first use needs no credential read.
159220
pub fn commit(
160221
&self,
161222
prepared: NewAppAgent,
162223
auth: &[String],
163224
credentials: &dyn Credentials,
164-
) -> Result<AppAgent> {
225+
) -> Result<(AppAgent, Secret)> {
165226
let auth = serde_json::to_string(auth).map_err(|_| "Invalid owner authorization")?;
166227
validate_attestation(&auth, prepared.key.pubkey())?;
167228
let tag: Vec<String> =
@@ -174,6 +235,10 @@ impl AppAgents {
174235
relay: prepared.relay,
175236
owner: prepared.owner,
176237
auth,
238+
agent_type: prepared.agent_type,
239+
name: prepared.name,
240+
profile: None,
241+
deleted: false,
177242
};
178243
let id = agent.credential_id();
179244
self.update(|agents| {
@@ -189,32 +254,60 @@ impl AppAgents {
189254
});
190255
if let Err(error) = saved {
191256
if credentials.delete(&id, &agent.pubkey).is_ok() {
192-
let _ = self.forget(&agent.pubkey);
257+
let _ = self.update(|agents| {
258+
agents.retain(|saved| saved.pubkey != agent.pubkey);
259+
Ok(())
260+
});
193261
}
194262
return Err(error);
195263
}
196-
Ok(agent)
264+
Ok((agent, prepared.key))
265+
}
266+
pub fn rename(&self, pubkey: &str, name: &str) -> Result<()> {
267+
let name = valid_name(name)?;
268+
self.edit(pubkey, |agent| agent.name = name)
197269
}
198-
/// Deletes the key, then forgets the identity, so a failed deletion can be
270+
/// Records a profile its community accepted, unless a newer one already is.
271+
pub fn published(&self, pubkey: &str, profile: Published) -> Result<()> {
272+
self.edit(pubkey, |agent| {
273+
if agent
274+
.profile
275+
.as_ref()
276+
.is_none_or(|last| last.created_at < profile.created_at)
277+
{
278+
agent.profile = Some(profile);
279+
}
280+
})
281+
}
282+
/// Deletes the key, then marks the row deleted, so a failed deletion can be
199283
/// retried. Absence is success.
200284
pub fn remove(&self, pubkey: &str, credentials: &dyn Credentials) -> Result<()> {
201285
let Some(agent) = self
202286
.list()?
203287
.into_iter()
204-
.find(|agent| agent.pubkey == pubkey)
288+
.find(|agent| agent.pubkey == pubkey && !agent.deleted)
205289
else {
206290
return Ok(());
207291
};
208292
credentials.delete(&agent.credential_id(), &agent.pubkey)?;
209-
self.forget(pubkey)
293+
self.edit(pubkey, |agent| agent.deleted = true)
210294
}
211-
fn forget(&self, pubkey: &str) -> Result<()> {
295+
/// Drops a deleted row once its community has been cleaned up.
296+
pub fn forget(&self, pubkey: &str) -> Result<()> {
212297
self.update(|agents| {
213-
agents.retain(|agent| agent.pubkey != pubkey);
298+
agents.retain(|agent| agent.pubkey != pubkey || !agent.deleted);
214299
Ok(())
215300
})
216301
}
217302
}
218303

304+
fn valid_name(name: &str) -> Result<String> {
305+
let name = name.trim();
306+
if name.is_empty() || name.len() > 256 || name.chars().any(char::is_control) {
307+
return Err("Name the agent in one line".into());
308+
}
309+
Ok(name.into())
310+
}
311+
219312
#[cfg(test)]
220313
mod tests;

0 commit comments

Comments
 (0)