Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion packages/api/src/agent-side/tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,16 @@ describe('runAgentTool', () => {
expect(getAgentTask).toHaveBeenCalledWith('org-1', 'agent-1', 'task-1');
});

test('a secret is given without its value, which only the person reads', async () => {
const {runAgentTool} = await import('./tools');
const secret = {id: 'secret-1', values: {name: 'API_KEY', value: 'sk-never-shown', note: 'For the reports'}, updatedAt: '2026-11-17T10:00:00.000Z'};
connector.get.mockResolvedValueOnce(Ok(secret));
connector.list.mockResolvedValueOnce(Ok({records: [secret], nextPage: null}));

expect((await runAgentTool(caller, 'vault-1', 'secrets_get', {id: 'secret-1'})).unwrap()).toEqual({record: {...secret, values: {name: 'API_KEY', note: 'For the reports'}}});
expect(JSON.stringify((await runAgentTool(caller, 'vault-1', 'secrets_list', {})).unwrap())).not.toContain('sk-never-shown');
});

test('a run for a task the agent does not have, or one finished already, is refused unlogged', async () => {
const {runAgentTool} = await import('./tools');
getAgentTask.mockResolvedValue(Ok(null));
Expand Down Expand Up @@ -806,11 +816,13 @@ describe("an integration's own tools", () => {
'entries_create',
'entries_update',
'entries_delete',
'secrets_list',
'secrets_get',
'entries_count',
'entries_purge',
]);
getAgentById.mockResolvedValue(Ok({...agent, grants: []}));
expect((await listAgentTools(signedIn, 'vault-1')).unwrap().map((tool) => tool.name)).toEqual(['entries_list', 'entries_get', 'entries_count']);
expect((await listAgentTools(signedIn, 'vault-1')).unwrap().map((tool) => tool.name)).toEqual(['entries_list', 'entries_get', 'secrets_list', 'secrets_get', 'entries_count']);
});

test('run by the runner with the params as given, for the caller on the connection, and logged by name with them', async () => {
Expand Down
24 changes: 23 additions & 1 deletion packages/api/src/agent-side/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,9 +440,31 @@ function runParamsTool(target: RunTarget, tool: ServerTool | ApiTool, params: un
});
}

// What a tool answers an agent, of whatever kind: never what is never given to one, as a vault's
// secret's value (`Field.secret`), which the person reads on the connection's page and a command
// uses by name. Taken out here, once, so that no kind of tool answers with it.
async function execute(run: ToolRun, params: Record<string, string>): Promise<Result<ToolResult, ApiError>> {
return (await executeKind(run, params)).map((answer) => withoutSecrets(run.target.collection, answer));
}

function withoutSecrets(collection: Collection, answer: ToolResult): ToolResult {
const hidden = collection.fields.filter((field) => field.secret).map((field) => field.key);
if (hidden.length === 0) {
return answer;
}
const hide = (record: DataRecord): DataRecord => ({...record, values: Object.fromEntries(Object.entries(record.values).filter(([key]) => !hidden.includes(key)))});
if ('records' in answer) {
return {...answer, records: answer.records.map(hide)};
}
if ('record' in answer && answer.record !== null) {
return {record: hide(answer.record)};
}
return answer;
}

// Only a command on values typed in runs on a collection that is only run; the catalog gives such
// a collection no other tool, so a run of another on it is a tool it doesn't have.
function execute(run: ToolRun, params: Record<string, string>): Promise<Result<ToolResult, ApiError>> {
function executeKind(run: ToolRun, params: Record<string, string>): Promise<Result<ToolResult, ApiError>> {
const {kind} = run.tool;
if (kind === 'newCommand') {
return newCommand(run, params);
Expand Down
2 changes: 2 additions & 0 deletions packages/api/src/connections/integrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {PLAID_INTEGRATION} from './plaid/integration';
import {POSTGRES_INTEGRATION} from './postgres/integration';
import {CHAT_INTEGRATION} from '../native/chat/integration';
import {FILES_INTEGRATION} from '../native/files/integration';
import {MEMORY_INTEGRATION} from '../native/memory/integration';
import {SANDBOX_INTEGRATION} from '../native/sandbox/integration';
import {VAULT_INTEGRATION} from '../native/vault/integration';

Expand Down Expand Up @@ -43,6 +44,7 @@ function modules(): Record<IntegrationId, ApiIntegration> {
plaid: PLAID_INTEGRATION,
sandbox: SANDBOX_INTEGRATION,
files: FILES_INTEGRATION,
memory: MEMORY_INTEGRATION,
chat: CHAT_INTEGRATION,
};
}
Expand Down
102 changes: 90 additions & 12 deletions packages/api/src/mcp/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ import {z} from 'zod';

import {type ApiError, Do} from '@proxy/utils';
import type {SignedInAgent} from '@proxy/db/agent';
import {CHAT_INTEGRATION_ID, FILES_INTEGRATION_ID, INTEGRATIONS, SANDBOX_INTEGRATION_ID, VAULT_ENTRY_TYPES, VAULT_INTEGRATION_ID} from '@proxy/integrations';
import {CHAT_INTEGRATION_ID, FILES_INTEGRATION_ID, INTEGRATIONS, MEMORY_ABOUT_TITLE, MEMORY_INTEGRATION_ID, SANDBOX_INTEGRATION_ID, VAULT_ENTRY_TYPES, VAULT_INTEGRATION_ID} from '@proxy/integrations';
import type {AgentConnection} from '@proxy/contracts/agent-side';

import {connectionSummary} from '../agent-side/summaries';
import {listAgentConnections} from '../agent-side/tools';
import {requireAppUrl} from '../oauth/oauth-config';
import {isAbout, readNotes} from '../native/memory/notes';
import {log} from '../observability/log';
import {agentScriptHost, type ScriptVia} from '../script/agent-host';
import {describeRun} from '../script/answer';
Expand Down Expand Up @@ -92,19 +93,21 @@ export const MCP_TOOLS: McpToolDefinition[] = [
];

// "Email, Granola, Notion, Linear, any custom MCP server": the services the agent's organization
// can connect, the vault, the Sandboxes, the Files and Chat being built in.
// can connect, the vault, the Sandboxes, the Files, the Memory and Chat being built in.
function connectableServices(): string {
const builtIn = [VAULT_INTEGRATION_ID, SANDBOX_INTEGRATION_ID, FILES_INTEGRATION_ID, CHAT_INTEGRATION_ID];
const builtIn = [VAULT_INTEGRATION_ID, SANDBOX_INTEGRATION_ID, FILES_INTEGRATION_ID, MEMORY_INTEGRATION_ID, CHAT_INTEGRATION_ID];
const offered = INTEGRATIONS.filter((integration) => !builtIn.includes(integration.id));
return offered.map((integration) => (integration.custom ? `any ${integration.name.charAt(0).toLowerCase()}${integration.name.slice(1)}` : integration.name)).join(', ');
}

const ENTRY_TYPES = VAULT_ENTRY_TYPES.join(' | ');

// The vaults as the agent's memory, those it may read: the person's own, for an agent of their
// own, and the ones members made, each by its name, the only ones a shared agent has; how to search
// and save, and with more than one, what goes where.
function vaultInstructions(connections: AgentConnection[]): string[] {
// The vaults, those the agent may read: the person's own, for an agent of their own, and the
// ones members made, each by its name, the only ones a shared agent has; how to search and save,
// and with more than one, what goes where. Where the agent has a memory, the vaults hold what the
// person gave their agents, details about them such as an address, and what the agent learns
// goes in memory; without one, as on a server without Files, the vaults are its memory.
function vaultInstructions(connections: AgentConnection[], remembers: boolean): string[] {
const vaults = connections.filter((connection) => connection.integrationId === VAULT_INTEGRATION_ID && connection.actions.includes('readEntries'));
if (vaults.length === 0) {
return [];
Expand All @@ -114,16 +117,88 @@ function vaultInstructions(connections: AgentConnection[]): string[] {
const whose = (vault: AgentConnection) => (vault.name === null ? 'the person’s' : `“${vault.name}”${vault.shared ? ', shared with others' : ''}`);
const named = vaults.map((vault) => `${vault.id}, ${whose(vault)}${writable(vault) ? '' : ', read-only'}`);
const own = vaults.some((vault) => vault.name === null);
const intro = remembers
? `Vaults hold what the person gave their agents, such as their address or a number of theirs: ${named.join('; ')}. Search one (entries_list {search}) before asking the person for such a detail.`
: `Vaults are the memory every agent shares: ${named.join('; ')}. Search one (entries_list {search}) before asking about the person or the organization.`;
const save = remembers
? `Save such a detail they tell you there (entries_create {title, type: ${ENTRY_TYPES}, content}).`
: `Save what will help next time (entries_create {title, type: ${ENTRY_TYPES}, content}); edit an entry rather than adding another.`;
return [
[
`Vaults are the memory every agent shares: ${named.join('; ')}. Search one (entries_list {search}) before asking about the person or the organization.`,
...(vaults.some(writable) ? [`Save what will help next time (entries_create {title, type: ${ENTRY_TYPES}, content}); edit an entry rather than adding another.`] : []),
intro,
...(vaults.some(writable) ? [save] : []),
...(vaults.some((vault) => !writable(vault)) ? ['For a read-only one, suggest adding it instead.'] : []),
...(vaults.length > 1 ? [own ? 'What is about the person alone goes in theirs; the rest, in the vault named for it.' : 'Save in the vault named for it.'] : []),
].join(' '),
];
}

// The vaults' secrets, where the agent may use or add them: that a sandbox command is given them
// by name, and that their values are never shown to it.
function secretInstructions(connections: AgentConnection[]): string[] {
const vaults = connections.filter((connection) => connection.integrationId === VAULT_INTEGRATION_ID);
const uses = vaults.some((vault) => vault.actions.includes('useSecrets'));
const adds = vaults.some((vault) => vault.actions.includes('writeSecrets'));
if (!uses && !adds) {
return [];
}
return [
[
...(uses
? [
'A vault’s secrets (secrets_list), such as API keys, are given to a sandbox command as environment variables by name: sandbox_exec {secrets: ["NAME"]}. Their values are kept from you: where a command prints one, it is shown as [secret NAME]. Don’t print them.',
]
: []),
...(adds ? ['Keep a key you made with secrets_create {name, value, note}: it can’t be read back.'] : []),
].join(' '),
];
}

// How long the index of the memory's notes every thread is given may be, in characters; the rest
// are found with notes_list.
const INDEX_CHARACTERS = 6_000;

// The memory, where the agent may read it: what it is for, About you whole and the other notes
// by their summaries, as they are when the thread starts (the built-in agent's prompt is kept as
// it was first sent: harness/inference.ts), and, where it may write, to keep what will help next
// time. What memory is for is said rather than what to write in it, which a model judges better
// for itself than by rules given in advance.
function memoryInstructions(connections: AgentConnection[]): Promise<Result<string[], ApiError>> {
return Do(async ($) => {
const memory = connections.find((connection) => connection.integrationId === MEMORY_INTEGRATION_ID && connection.actions.includes('readMemory'));
if (!memory) {
return [];
}
const notes = $(await readNotes(memory.id));
const about = notes.find((note) => isAbout(note.title));
const others = notes.filter((note) => note !== about);
const index: string[] = [];
let length = 0;
for (const note of others) {
const line = `- ${note.id}: ${note.title}${note.summary === '' ? '' : ` — ${note.summary}`}`;
if (length + line.length > INDEX_CHARACTERS) {
index.push(`- and ${others.length - index.length} more: notes_list {search} finds them`);
break;
}
index.push(line);
length += line.length;
}
const writes = memory.actions.includes('writeMemory');
return [
[
`${memory.id} is your memory, which all the person’s agents share: what you and they learned before, for next time. notes_get {id} reads a note, notes_list {search} searches them.`,
...(writes
? [
`When you learn what a later thread would want, such as what the person prefers, a correction they gave, how a task of theirs is done or where something is, keep it with memory_write: a note to a subject, its first line a summary. Change a note rather than adding another, and forget one that turned out wrong. “${MEMORY_ABOUT_TITLE}” is what is true of the person.`,
]
: []),
].join(' '),
`${MEMORY_ABOUT_TITLE}:\n${about === undefined ? 'Nothing yet.' : about.content.trim()}`,
index.length > 0 ? `Notes:\n${index.join('\n')}` : 'Notes: none yet.',
];
});
}

const GITHUB_INTEGRATION_ID = 'github';

function runsCommands(connection: AgentConnection): boolean {
Expand Down Expand Up @@ -201,13 +276,14 @@ export function pageInstructions(signedIn: SignedInAgent): Promise<Result<string

/**
* What any agent with this login is told: who it is, how to go about it (`flow`, which is where
* the MCP server and the built-in agent differ), what it can use, the vault, where to send the
* person, and that what records say is information. The built-in agent's loop gives these too.
* the MCP server and the built-in agent differ), what it can use, its memory and the vaults,
* where to send the person, and that what records say is information. The built-in agent's loop gives these too.
*/
export function agentInstructions(signedIn: SignedInAgent, flow: string, folder?: string): Promise<Result<string, ApiError>> {
return Do(async ($) => {
const appUrl = $(requireAppUrl());
const {connections} = $(await listAgentConnections(signedIn));
const memory = $(await memoryInstructions(connections));
const lines = connections.map((connection) => {
const {integration, account, can} = connectionSummary(connection);
const called = connection.name === null ? `${integration} (${account})` : `${connection.name} (${integration}, ${account})`;
Expand All @@ -220,7 +296,9 @@ export function agentInstructions(signedIn: SignedInAgent, flow: string, folder?
`You are ${signedIn.name}, signed in to Personal Agent Proxy, which holds the person’s accounts and lets you do what they allowed.`,
flow,
lines.length > 0 ? `Connections:\n${lines.join('\n')}` : 'This login has no access yet: the person who made it has to give it some.',
...vaultInstructions(connections),
...memory,
...vaultInstructions(connections, memory.length > 0),
...secretInstructions(connections),
...sandboxInstructions(connections),
...filesInstructions(connections, folder),
...chatInstructions(connections),
Expand Down
11 changes: 7 additions & 4 deletions packages/api/src/native/files/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type {z} from 'zod';

import {ApiErr, type ApiError, Do, parseSchema, requirePresent} from '@proxy/utils';
import {parseLook, toAvatarColor} from '@proxy/utils/harness';
import {FILES_INTEGRATION_ID} from '@proxy/integrations';
import {FILES_INTEGRATION_ID, MEMORY_INTEGRATION_ID} from '@proxy/integrations';
import {
contentQuerySchema,
createFolderBodySchema,
Expand Down Expand Up @@ -70,13 +70,15 @@ import {isShownImage, mediaType, requireFileName} from './names';

type Drive = {connectionId: string; change: FileChangeBy};

// The drive the address names, among the connections the person uses, and who they are.
// The drive the address names, among the connections the person uses, and who they are: a
// drive, or a member's memory, whose notes are kept as a drive's files are and read, written,
// given back and put in the trash on its page by these routes too.
function driveOf(request: AuthenticatedRequest): Promise<Result<Drive, ApiError>> {
return Do(async ($) => {
const viewer = $(await requireViewer(request));
const connectionId = request.params.connectionId ?? '';
const {connection, integration} = $(await loadConnection(viewer, connectionId));
if (integration.id !== FILES_INTEGRATION_ID) {
if (integration.id !== FILES_INTEGRATION_ID && integration.id !== MEMORY_INTEGRATION_ID) {
return $(Err(ApiErr.notFound('connection', connectionId)));
}
return {connectionId: connection.id, change: {orgId: connection.orgId, connectionId: connection.id, by: {userId: viewer.userId}}};
Expand All @@ -101,7 +103,8 @@ function toFile(entry: FileEntry, above?: FileNodeRow[]): DriveFile {
};
}

function toMaker(maker: FileMakerRow): FileMaker {
/** An agent that made what a file holds, as the person's pages draw it. */
export function toMaker(maker: FileMakerRow): FileMaker {
if (maker.kind === 'persona') {
return {...maker, look: parseLook(maker.look), color: toAvatarColor(maker.color)};
}
Expand Down
43 changes: 43 additions & 0 deletions packages/api/src/native/memory/connector.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import {Err} from 'ts-results-es';

import {ApiErr, Do} from '@proxy/utils';

import {type DataRecord, type RecordStore, requireFirstPage} from '../../records/connector';
import {matches, type Note, readNotes, writtenBy} from './notes';

/**
* A memory's notes as records, only read here: the list with each note's summary, searched by
* the words in its title and text, and a note opened whole, with the version memory_write has to
* name to change it. Every write is a tool of the integration's own (tools.ts), which names who
* wrote it.
*/

function toRecord(note: Note, content: string): DataRecord {
const modified = note.modifiedAt.toISOString();
return {
id: note.id,
values: {title: note.title, summary: note.summary, content, version: note.version, writtenBy: writtenBy(note), modified},
updatedAt: modified,
};
}

/** The notes collection's connector. */
export const memoryConnector = {
list: (target, query) =>
Do(async ($) => {
$(requireFirstPage(query));
const notes = $(await readNotes(target.connection.id));
const search = query.search?.trim();
const found = search ? notes.filter((note) => matches(note, search)) : notes;
return {records: found.map((note) => toRecord(note, '')), nextPage: null};
}),
get: (target, recordId) =>
Do(async ($) => {
const notes = $(await readNotes(target.connection.id));
const note = notes.find((candidate) => candidate.id === recordId);
if (!note) {
return $(Err(ApiErr.notFound('note', recordId, 'notes_list lists them.')));
}
return toRecord(note, note.content);
}),
} satisfies RecordStore;
10 changes: 10 additions & 0 deletions packages/api/src/native/memory/integration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type {ApiIntegration} from '../../connections/integration';
import {memoryConnector} from './connector';
import {runMemoryForget, runMemoryWrite} from './tools';

/** Memory, in Personal Agent Proxy itself: a member's notes as records, read, and every write a tool of its own. */
export const MEMORY_INTEGRATION: ApiIntegration = {
id: 'memory',
connectors: {notes: memoryConnector},
tools: {memory_write: runMemoryWrite, memory_forget: runMemoryForget},
};
34 changes: 34 additions & 0 deletions packages/api/src/native/memory/notes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import {describe, expect, test} from 'bun:test';

import {isAbout, matches, nameOf, requireContent, summaryOf, titleOf, type Note} from './notes';

const note = (title: string, content: string): Note => ({id: 'note-1', title, summary: summaryOf(content), content, version: 'v1', modifiedAt: new Date('2026-11-17T10:00:00Z'), makers: []});

describe('a note', () => {
test('is kept as its title and .md, About you by its own spelling', () => {
expect(nameOf(' Pricing review notes ').unwrap()).toBe('Pricing review notes.md');
expect(nameOf('about YOU').unwrap()).toBe('About you.md');
expect(titleOf('Pricing review notes.md')).toBe('Pricing review notes');
expect(isAbout('About you')).toBe(true);
expect(nameOf(' ').isErr()).toBe(true);
expect(nameOf('a'.repeat(121)).isErr()).toBe(true);
});

test('is summed up by its first line with words in it, without a heading’s marks', () => {
expect(summaryOf('\n## How releases go out\n\nTag, then deploy.')).toBe('How releases go out');
expect(summaryOf('x'.repeat(500)).length).toBe(200);
});

test('needs content, and no more than its title allows', () => {
expect(requireContent('Releases', ' ').isErr()).toBe(true);
expect(requireContent('Releases', 'x'.repeat(20_000)).isOk()).toBe(true);
expect(requireContent('Releases', 'x'.repeat(20_001)).isErr()).toBe(true);
expect(requireContent('About you', 'x'.repeat(3_001)).isErr()).toBe(true);
});

test('is found by every word of a search, in its title or its text, in any case', () => {
const found = note('Releases', 'Tag the commit, then deploy from main.');
expect(matches(found, 'releases DEPLOY')).toBe(true);
expect(matches(found, 'deploy staging')).toBe(false);
});
});
Loading
Loading