Skip to content
Merged
1 change: 1 addition & 0 deletions docs/domains/people.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ The one question Participation asks People about a sender. The answer is a perso

- A stranger and a dismissed account both answer nobody. The difference matters only to the guardian, in which accounts are shown for them to decide about.
- Participation asks it about the sender of every message a wake hands an agent, each time a turn runs.
- An agent that meets someone it does not recognize reads who they are by name, with the guardian's notes on them. Sentinel, which answers senders Rome does not trust, reads the sender's own notes on each message instead, and no one else's.

## Decided against

Expand Down
1 change: 1 addition & 0 deletions packages/core/agents/main.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,6 @@ systemPromptPrefix: |
When a Rome platform capability fails or is missing in a way only the platform can fix, report it with `system:send_feedback`.
Use `system:send_message` to proactively send messages through any registered channel.
Always check memory for relevant context before responding.
Each message names who said it. When a message comes from, or mentions, someone you do not recognize, read who they are with `core:read_person` before you answer.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] design — Main no longer reliably sees the notes of the person it is replying to

Before this PR, a connection's 1:1 DM always carried that sender's notes. Those notes can include the guardian's instructions for handling the person. Now main only reads them if the model decides the sender is "someone you do not recognize", and a sender labelled Ana (Ana Lopez, inner circle) will usually look recognized. Suggestion: in handleTrustedMessage, prepend the same <sender>${buildSenderInfo(...)}</sender> block that sentinel gets, and add "sender" to STICKY_HEADERS (packages/core/src/core/sticky-headers.ts), so it is only re-sent when the speaker changes, the way concierge_owner already works. Keep core:read_person for people who are only mentioned or who appear in caught-up history.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed, on purpose. Taking the person's notes out of the system prompt and having main read them with core:read_person when it meets someone it does not recognize is the design the owner chose, so the runtime no longer decides which notes main reads. A 1:1 DM still names the sender on every message (who="Ana Lopez, inner circle"), so main knows who it is talking to and can read their notes in one call. I've raised the DM case with the owner as a design question; if they want the notes back for DMs it will be a follow-up.

When the guardian asks you to change your own name, call `core:set_agent_name` with `execute_action`. Do not edit the `Agent Name` line in IDENTITY.md: the setting owns it.
Be proactive about journaling important interactions.
2 changes: 1 addition & 1 deletion packages/core/src/agent/application/agent-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ import { createTurnsById, type TurnsById } from "./turns-by-id.js";

export interface AgentSessionKey {
agentName: string;
/** e.g. `webchat:<id>`, `telegram:<chatId>`, `sentinel:<channel>:<thread>`. */
/** e.g. `webchat:<id>`, `telegram:<chatId>`, `sentinel:<channel>:<thread>:<sender>`. */
channelThreadKey: string;
}

Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/apps/actions/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,9 @@ const COORDINATION_ACTIONS: ReadonlySet<string> = new Set([
// roots, outside this action's context.
"system:publish_event",
"core:set_agent_name",
// Reads a person and their notes (people/read-person.ts), which only main
// registers.
"core:read_person",
"core:show_file",
"core:app_connection_read",
"core:app_connection_write",
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ import {
import { chatPromptFacts } from "./core/chat-prompt-facts.js";
import { ROME_AGENT_TRAITS } from "./concierge/agent-traits.js";
import { registerAgentNameAction } from "./people/agent-name.js";
import { registerReadPersonAction } from "./people/read-person.js";
import { registerShowFileAction } from "./assets/show-file-action.js";
import { ConciergeService } from "./concierge/service.js";
import { chatsTaskChatMessages } from "./concierge/task-chat.js";
Expand Down Expand Up @@ -1390,6 +1391,10 @@ async function main() {

registerShowFileAction(actionRegistry);
registerTaskRunAction(actionRegistry, concierge);
registerReadPersonAction(actionRegistry, {
people: peopleRepo,
ownerOfChat: (chatId) => concierge.ownerOfChat(chatId),
});
const agentNameEvents = registerAgentNameAction(actionRegistry, {
settingsRepo,
ownerOfChat: (chatId) => concierge.ownerOfChat(chatId),
Expand Down
115 changes: 115 additions & 0 deletions packages/core/src/people/read-person.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { afterEach, beforeEach, describe, expect, it, rs } from "@rstest/core";
import { ActionEngine, type ActionRunContext } from "../apps/actions/engine.js";
import { ActionRegistryImpl } from "../apps/actions/registry.js";
import { PeopleRepository } from "../db/repositories/people.js";
import { createActionEngineRepos, createTestDb, type TestDb } from "../test/db.js";
import { READ_PERSON_ACTION, registerReadPersonAction } from "./read-person.js";

type Actor = NonNullable<ActionRunContext["actor"]>;

const guardian: Actor = { kind: "guardian", userId: "guardian", via: "cookie" };
const visitor: Actor = { kind: "visitor", accountId: "visitor", email: "visitor@example.test" };

let testDb: TestDb;
let people: PeopleRepository;
let registry: ActionRegistryImpl;
let engine: ActionEngine;
let notes: Map<string, string>;

beforeEach(async () => {
testDb = createTestDb();
notes = new Map([["memory/relationship/ana.md", "Runs the venue."]]);
people = new PeopleRepository(testDb.db);
registry = new ActionRegistryImpl();
registerReadPersonAction(registry, {
people,
ownerOfChat: async (chatId) =>
chatId === "visitor-chat"
? "visitor:visitor"
: chatId === "guardian-chat"
? "guardian"
: null,
readNotes: async (path) => notes.get(path) ?? null,
});
engine = new ActionEngine(registry, createActionEngineRepos(testDb.db), {
processRole: "main",
workerWarmPoolSize: 0,
isFirstPartyAction: (name) => name === READ_PERSON_ACTION,
actionWorkerFork: rs.fn(() => {
throw new Error("Reading a person must run in main");
}),
});
});

afterEach(() => testDb.close());

const read = (name: unknown, context: ActionRunContext = {}) =>
engine.run(READ_PERSON_ACTION, { name }, context);

describe("core:read_person", () => {
it("reads every person by that name, ignoring case, with their accounts and notes", async () => {
await people.create({
displayName: "Ana Lopez",
bondLevel: "inner-circle",
profilePath: "memory/relationship/ana.md",
links: [{ platform: "discord", id: "ana" }],
});
const bob = await people.create({ displayName: "Bob", bondLevel: "acquaintance" });
// A person created with no profile path keeps their notes in the file
// named after their id.
notes.set(`memory/relationship/${bob}.md`, "Plays bass.");

expect(await read("ana lopez", { actor: guardian })).toEqual({
status: "ok",
data: {
people: [
{
name: "Ana Lopez",
bondLevel: "inner-circle",
accounts: [{ platform: "discord", id: "ana" }],
notes: "Runs the venue.",
},
],
},
});
expect(await read("Bob", { actor: guardian })).toMatchObject({
status: "ok",
data: { people: [{ name: "Bob", notes: "Plays bass." }] },
});
});

it("answers no one for a name nobody has", async () => {
expect(await read("Nobody", { actor: guardian })).toEqual({
status: "ok",
data: { people: [] },
});
});

it("refuses a visitor, and a turn no one started in a chat a visitor owns", async () => {
await people.create({ displayName: "Ana Lopez", bondLevel: "inner-circle" });
expect((await read("Ana Lopez", { actor: visitor })).status).toBe("error");
const visitorChat = { channel: "webchat", threadId: "visitor-chat" };
expect((await read("Ana Lopez", { channelContext: visitorChat })).status).toBe("error");
const goneChat = { channel: "webchat", threadId: "gone-chat" };
expect((await read("Ana Lopez", { channelContext: goneChat })).status).toBe("error");
});

it("refuses a turn with neither an actor nor a chat, such as an agent summoned from a visitor's task", async () => {
await people.create({ displayName: "Ana Lopez", bondLevel: "inner-circle" });
expect((await read("Ana Lopez", {})).status).toBe("error");
});

it("reads for a turn no one started in the guardian's chat or a chat on a connection", async () => {
await people.create({ displayName: "Ana Lopez", bondLevel: "inner-circle" });
const guardianChat = { channel: "webchat", threadId: "guardian-chat" };
expect((await read("Ana Lopez", { channelContext: guardianChat })).status).toBe("ok");
const group = { channel: "discord", threadId: "group-1" };
expect((await read("Ana Lopez", { channelContext: group })).status).toBe("ok");
});

it("is available through the main agent wildcard", () => {
expect(registry.getForAgent(["*"]).map((action) => action.config.name)).toContain(
READ_PERSON_ACTION,
);
});
});
103 changes: 103 additions & 0 deletions packages/core/src/people/read-person.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// The agent's way to read who a person is: their bond level, accounts and the
// notes the guardian keeps on them. Vocabulary: docs/domains/people.md.

import { readFile } from "node:fs/promises";
import { actionExecutionContext } from "../apps/actions/context.js";
import type { ActionRegistry } from "../apps/actions/types.js";
import type { PeopleRepository, Person } from "../db/repositories/people.js";
import { personProfilePath, resolveProfileMemoryPath } from "../profile-memory.js";

export const READ_PERSON_ACTION = "core:read_person";

/** A person as the agent reads them. `notes` is null when the guardian keeps
* none on them. */
export interface PersonAsRead {
name: string;
bondLevel: Person["bondLevel"];
accounts: { platform: string; id: string; delegate?: true }[];
notes: string | null;
}

/** Registers `core:read_person`, which the agent calls to learn who someone
* it does not recognize is. */
export function registerReadPersonAction(
actions: Pick<ActionRegistry, "register">,
deps: {
people: Pick<PeopleRepository, "all">;
/** Whose chat it is ("guardian" or "visitor:<account>"), or null for a
* chat that no longer exists. */
ownerOfChat(chatId: string): Promise<string | null>;
/** The notes at `path` under the memory root, or null when there are none. */
readNotes?: (path: string) => Promise<string | null>;
},
): void {
const readNotes = deps.readNotes ?? readNotesFile;
actions.register({
config: {
name: READ_PERSON_ACTION,
type: "system",
description:
"Read who a person is: their bond level, their accounts, and the guardian's notes on them. Call it when a message comes from, or mentions, someone you do not recognize. Pass the person's name as Rome names the sender, before the bond level: `Ana Lopez` from `who=\"Ana Lopez, inner circle\"` or from `Ana [Ana Lopez, inner circle]`. A sender marked `not linked` is nobody the guardian tracks and has no notes.",
complexity: "simple",
speed: "fast",
reliability: "high",
sideEffects: "read-only",
},
inputSchema: {
type: "object",
required: ["name"],
properties: {
name: { type: "string", description: "The person's name, matched ignoring case." },
},
additionalProperties: false,
},
execute: async (args) => {
// The notes are the guardian's own, so a visitor never reads them: not
// as the turn's actor, and not through a turn no one started in a chat
// the visitor owns, such as a task the Concierge runs for them. A turn
// with neither an actor nor a chat, such as an agent summoned from that
// task, cannot show it is the guardian's and is refused too. A chat on a
// connection has no owner and is the guardian's agent's.
const context = actionExecutionContext.getStore();
const refused = {
status: "error" as const,
error: "Only the guardian's agents can read a person's notes.",
};
if (context?.actor && context.actor.kind !== "guardian") return refused;
const thread = context?.channelContext;
if (!context?.actor && !thread) return refused;
if (thread?.channel === "webchat") {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 29c95ca, by failing closed. core:read_person now refuses a turn with neither an actor nor a chat, so a summoned agent cannot read notes unless its turn shows it is the guardian's. The trade-off is that a summoned agent can't use the tool even when a guardian chat summoned it. Carrying the caller's chat through system:summon would fix that, but it changes summon for every action, so I've left it for a follow-up. A new test covers the actorless, chatless turn.

const owner = thread.threadId ? await deps.ownerOfChat(thread.threadId) : null;
if (owner !== "guardian") return refused;
}
const name = typeof args.name === "string" ? args.name.trim() : "";
if (!name) return { status: "error", error: "Pass the person's name." };
const wanted = name.toLowerCase();
const matches = (await deps.people.all()).filter(
(person) => person.displayName.trim().toLowerCase() === wanted,
);
const people: PersonAsRead[] = await Promise.all(
matches.map(async (person) => ({
name: person.displayName,
bondLevel: person.bondLevel,
accounts: person.links.map(({ platform, id, delegate }) => ({
platform,
id,
...(delegate ? { delegate } : {}),
})),
notes: await readNotes(personProfilePath(person)),
})),
);
return { status: "ok", data: { people } };
},
});
}

async function readNotesFile(path: string): Promise<string | null> {
try {
const notes = (await readFile(resolveProfileMemoryPath(path), "utf8")).trim();
return notes || null;
} catch {
return null;
}
}
9 changes: 3 additions & 6 deletions packages/core/src/people/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { readdir } from "node:fs/promises";
import type { Account } from "@rome-os/app-runtime";
import type { AccountSendState, PersonResource } from "@rome/api-types/people";
import type { Message } from "@rome/api-types/message";
import { getRelationshipDir, personProfileFileName, RELATIONSHIP_DIR } from "../profile-memory.js";
import { getRelationshipDir, personProfilePath, RELATIONSHIP_DIR } from "../profile-memory.js";
import type { AccountNames } from "../chats/accounts/account-names.js";
import type { Channels, PlatformOfChannel } from "../chats/connected-accounts/connected-account.js";
import type { MessageAccount } from "../chats/history/messages.js";
Expand Down Expand Up @@ -149,11 +149,8 @@ async function memoryProfilePaths(persons: readonly PersonRow[]): Promise<(strin
const written = new Set(await readdir(getRelationshipDir()).catch(() => []));

return persons.map((person) => {
const stored = person.profilePath?.startsWith(`${RELATIONSHIP_DIR}/`)
? person.profilePath.slice(RELATIONSHIP_DIR.length + 1)
: null;
const fileName = stored ?? personProfileFileName(person.id);
return written.has(fileName) ? `${RELATIONSHIP_DIR}/${fileName}` : null;
const path = personProfilePath(person);
return written.has(path.slice(RELATIONSHIP_DIR.length + 1)) ? path : null;
});
}

Expand Down
13 changes: 13 additions & 0 deletions packages/core/src/profile-memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,19 @@ export function personProfileFileName(personId: string): string {
return `${personId}.md`;
}

/**
* Where a person's notes live under the memory root: the stored profile path
* when it is inside the relationship directory, and otherwise the file named
* after the person's id, which the agent writes when it has something to
* remember. The file may not exist.
*/
export function personProfilePath(person: { id: string; profilePath: string | null }): string {
const stored = person.profilePath?.startsWith(`${RELATIONSHIP_DIR}/`)
? person.profilePath.slice(RELATIONSHIP_DIR.length + 1)
: null;
return `${RELATIONSHIP_DIR}/${stored ?? personProfileFileName(person.id)}`;
}

/** The relationship directory on disk, for reading or writing the files in it. */
export function getRelationshipDir(): string {
return resolveProfileMemoryPath(RELATIONSHIP_DIR);
Expand Down
Loading
Loading