diff --git a/packages/api/src/agent-side/tools.test.ts b/packages/api/src/agent-side/tools.test.ts index fc898226..f386f7a5 100644 --- a/packages/api/src/agent-side/tools.test.ts +++ b/packages/api/src/agent-side/tools.test.ts @@ -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)); @@ -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 () => { diff --git a/packages/api/src/agent-side/tools.ts b/packages/api/src/agent-side/tools.ts index 69ffff0e..587e8dc1 100644 --- a/packages/api/src/agent-side/tools.ts +++ b/packages/api/src/agent-side/tools.ts @@ -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): Promise> { + 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): Promise> { +function executeKind(run: ToolRun, params: Record): Promise> { const {kind} = run.tool; if (kind === 'newCommand') { return newCommand(run, params); diff --git a/packages/api/src/connections/integrations.ts b/packages/api/src/connections/integrations.ts index 59f6f549..d02b2c35 100644 --- a/packages/api/src/connections/integrations.ts +++ b/packages/api/src/connections/integrations.ts @@ -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'; @@ -43,6 +44,7 @@ function modules(): Record { plaid: PLAID_INTEGRATION, sandbox: SANDBOX_INTEGRATION, files: FILES_INTEGRATION, + memory: MEMORY_INTEGRATION, chat: CHAT_INTEGRATION, }; } diff --git a/packages/api/src/mcp/tools.ts b/packages/api/src/mcp/tools.ts index 2270aeae..444bac97 100644 --- a/packages/api/src/mcp/tools.ts +++ b/packages/api/src/mcp/tools.ts @@ -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'; @@ -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 []; @@ -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> { + 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 { @@ -201,13 +276,14 @@ export function pageInstructions(signedIn: SignedInAgent): Promise> { 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})`; @@ -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), diff --git a/packages/api/src/native/files/route.ts b/packages/api/src/native/files/route.ts index 15550779..9ce0aedc 100644 --- a/packages/api/src/native/files/route.ts +++ b/packages/api/src/native/files/route.ts @@ -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, @@ -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> { 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}}}; @@ -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)}; } diff --git a/packages/api/src/native/memory/connector.ts b/packages/api/src/native/memory/connector.ts new file mode 100644 index 00000000..a61971f7 --- /dev/null +++ b/packages/api/src/native/memory/connector.ts @@ -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; diff --git a/packages/api/src/native/memory/integration.ts b/packages/api/src/native/memory/integration.ts new file mode 100644 index 00000000..17f1d393 --- /dev/null +++ b/packages/api/src/native/memory/integration.ts @@ -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}, +}; diff --git a/packages/api/src/native/memory/notes.test.ts b/packages/api/src/native/memory/notes.test.ts new file mode 100644 index 00000000..9d339c27 --- /dev/null +++ b/packages/api/src/native/memory/notes.test.ts @@ -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); + }); +}); diff --git a/packages/api/src/native/memory/notes.ts b/packages/api/src/native/memory/notes.ts new file mode 100644 index 00000000..0b101289 --- /dev/null +++ b/packages/api/src/native/memory/notes.ts @@ -0,0 +1,110 @@ +import {Err, Ok, type Result} from 'ts-results-es'; + +import {ApiErr, type ApiError, Do} from '@proxy/utils'; +import {MEMORY_ABOUT_CHARACTERS, MEMORY_ABOUT_TITLE, MEMORY_NOTE_CHARACTERS, MEMORY_SUMMARY_CHARACTERS} from '@proxy/integrations'; +import {type FileMaker, listFileMakers, listTopFiles, type TopFile} from '@proxy/db/files'; + +import {requireFileName} from '../files/names'; +import {readVersion} from '../files/text'; + +/** + * A member's memory as notes: each a file at the top of its connection's drive, called by its + * title and .md, holding Markdown whose first line is its summary. Read whole here, all of them + * at once, since there are few and they are short: to search them, and for what every thread is + * given (mcp/tools.ts). Who wrote a note is its file's journal's, as a drive's is (db/files.ts). + */ + +/** How many notes are read at most, the latest changed first. */ +export const MAX_NOTES = 500; + +/** How long a title may be. */ +const MAX_TITLE = 120; + +/** A note as it is now, with the agents that wrote it, the latest first. */ +export type Note = {id: string; title: string; summary: string; content: string; version: string; modifiedAt: Date; makers: FileMaker[]}; + +const EXTENSION = '.md'; + +/** A note's title, from its file's name. */ +export function titleOf(name: string): string { + return name.endsWith(EXTENSION) ? name.slice(0, -EXTENSION.length) : name; +} + +/** Whether the title is the note every thread is given whole. */ +export function isAbout(title: string): boolean { + return title.trim().toLowerCase() === MEMORY_ABOUT_TITLE.toLowerCase(); +} + +/** The file a title is kept as, About you by its own spelling however it was written; refused where it can't be a file's name. */ +export function nameOf(title: string): Result { + const trimmed = title.trim(); + if (trimmed === '') { + return Err(ApiErr.validationError('A note needs a title')); + } + if (trimmed.length > MAX_TITLE) { + return Err(ApiErr.validationError(`A note’s title is at most ${MAX_TITLE} characters`)); + } + return requireFileName(`${isAbout(trimmed) ? MEMORY_ABOUT_TITLE : trimmed}${EXTENSION}`); +} + +/** A note's summary: its first line with words in it, without a heading's marks, cut short where long. */ +export function summaryOf(content: string): string { + const line = content.split('\n').find((candidate) => candidate.trim() !== '') ?? ''; + const plain = line.replace(/^\s*#+\s*/, '').trim(); + return plain.length > MEMORY_SUMMARY_CHARACTERS ? `${plain.slice(0, MEMORY_SUMMARY_CHARACTERS - 1)}…` : plain; +} + +/** What a note may hold: something, and no more than its title allows. */ +export function requireContent(title: string, content: string): Result { + if (content.trim() === '') { + return Err(ApiErr.validationError('A note needs content: memory_forget forgets one')); + } + const most = isAbout(title) ? MEMORY_ABOUT_CHARACTERS : MEMORY_NOTE_CHARACTERS; + if (content.length > most) { + return Err(ApiErr.validationError(`That is ${content.length} characters, and “${title.trim()}” holds at most ${most}: shorten it, moving detail into notes of its own`)); + } + return Ok(undefined); +} + +// A file's text as a note's; a file that can't be read as text, which nothing here writes, has none. +function readNote(file: TopFile): Promise, ApiError>> { + return Do(async ($) => { + const reading = $(await readVersion(file.name, file.head)); + const content = 'text' in reading ? reading.text : ''; + return {id: file.id, title: titleOf(file.name), summary: summaryOf(content), content, version: file.head.id, modifiedAt: file.updatedAt}; + }); +} + +/** Every note of the memory, the latest changed first, at most MAX_NOTES. */ +export function readNotes(connectionId: string): Promise> { + return Do(async ($) => { + const files = $(await listTopFiles(connectionId, MAX_NOTES)); + const [read, makers] = await Promise.all([ + Promise.all(files.map(readNote)), + listFileMakers( + connectionId, + files.map((file) => file.id), + ), + ]); + const byFile = $(makers); + return read.map((note) => { + const value = $(note); + return {...value, makers: byFile.get(value.id) ?? []}; + }); + }); +} + +/** Whether a note has every word of a search in its title or its text, in any case. */ +export function matches(note: Note, search: string): boolean { + const words = search.toLowerCase().split(/\s+/).filter(Boolean); + const text = `${note.title}\n${note.content}`.toLowerCase(); + return words.every((word) => text.includes(word)); +} + +/** Who wrote a note, in words: its agents, the latest first, or the person where none did. */ +export function writtenBy(note: Note): string { + if (note.makers.length === 0) { + return 'the person'; + } + return note.makers.map((maker) => maker.name).join(', '); +} diff --git a/packages/api/src/native/memory/route.ts b/packages/api/src/native/memory/route.ts new file mode 100644 index 00000000..ecc68b69 --- /dev/null +++ b/packages/api/src/native/memory/route.ts @@ -0,0 +1,41 @@ +import {Err, type Result} from 'ts-results-es'; +import type {z} from 'zod'; + +import {ApiErr, type ApiError, Do} from '@proxy/utils'; +import {MEMORY_INTEGRATION_ID} from '@proxy/integrations'; +import type {memorySchema} from '@proxy/contracts/memory'; + +import {loadConnection} from '../../records/target'; +import type {AuthenticatedRequest} from '../../server/middleware/require-auth'; +import {requireViewer} from '../../utils/user-org'; +import {toMaker} from '../files/route'; +import {isAbout, readNotes} from './notes'; + +/** + * A member's memory as the person reads it, on its connection's page: every note, whole, with + * the agents that wrote it. What they do to one, writing it, giving an earlier version back and + * putting it in the trash, goes through the drive's routes (native/files/route.ts). + */ +export function handleMemoryRoute(request: AuthenticatedRequest): Promise, ApiError>> { + return Do(async ($) => { + const viewer = $(await requireViewer(request)); + const connectionId = request.params.connectionId ?? ''; + const {connection, integration} = $(await loadConnection(viewer, connectionId)); + if (integration.id !== MEMORY_INTEGRATION_ID) { + return $(Err(ApiErr.notFound('connection', connectionId))); + } + const notes = $(await readNotes(connection.id)); + return { + notes: notes.map((note) => ({ + id: note.id, + title: note.title, + summary: note.summary, + content: note.content, + version: note.version, + modifiedAt: note.modifiedAt.toISOString(), + makers: note.makers.map(toMaker), + about: isAbout(note.title), + })), + }; + }); +} diff --git a/packages/api/src/native/memory/tools.ts b/packages/api/src/native/memory/tools.ts new file mode 100644 index 00000000..29c2d1ca --- /dev/null +++ b/packages/api/src/native/memory/tools.ts @@ -0,0 +1,70 @@ +import {Err, type Result} from 'ts-results-es'; +import {z} from 'zod'; + +import {ApiErr, type ApiError, Do, parseSchema} from '@proxy/utils'; +import {createFile, type FileChangeBy, findPath, trashFile, writeFile} from '@proxy/db/files'; + +import type {NativeToolRun, NativeToolRunner} from '../tool'; +import {requireFile} from '../files/connector'; +import {maxFileBytes, storeText} from '../files/content'; +import {nameOf, requireContent, titleOf} from './notes'; + +/** + * The memory's tools: writing a note, new or over the version read, and forgetting one, each as + * the agent, for the task the call is run for, which the drive's journal keeps (db/files.ts), so + * the person sees which of their agents wrote what, and every version before stays. + */ + +const NOTE_TYPE = 'text/markdown'; + +function changeOf({caller, connection}: NativeToolRun): FileChangeBy { + return {orgId: connection.orgId, connectionId: connection.id, by: {agentId: caller.agent.agentId, taskId: caller.taskId}}; +} + +function read(schema: z.ZodType, tool: string, takes: string, params: Record): Result { + return parseSchema(schema, params).mapErr((error) => ApiErr.validationError(`${tool} takes ${takes}${error.kind === 'parse_error' ? `: ${error.message}` : ''}`)); +} + +const writeSchema = z.object({title: z.string(), content: z.string(), version: z.string().min(1).optional()}); + +/** memory_write: a note written, new under a title none has, or over the version the agent read. */ +export const runMemoryWrite: NativeToolRunner = (run) => + Do(async ($): Promise => { + const {title: raw, content, version} = $(read(writeSchema, 'memory_write', 'title and content, and version to change a note', run.params)); + const name = $(nameOf(raw)); + const title = titleOf(name); + $(requireContent(title, content)); + const {found, missing} = $(await findPath(run.connection.id, [name])); + const note = missing.length === 0 ? found[0] : undefined; + if (note !== undefined && version === undefined) { + return $(Err(ApiErr.conflict(`There is a note called “${title}” already, ${note.id}: read it with notes_get, then write it with the version it answers with.`))); + } + if (note !== undefined && note.head?.id !== version) { + return $(Err(ApiErr.conflict(`“${title}” changed since that version was read: it holds ${note.head?.id ?? 'nothing'} now. Read it again with notes_get, then write.`))); + } + if (note === undefined && version !== undefined) { + return $(Err(ApiErr.notFound('note', title, 'No note has that title: leave version out to make one.'))); + } + const stored = $(await storeText(run.connection.orgId, content, maxFileBytes())); + const kept = {blobId: stored.blobId, size: stored.size, type: NOTE_TYPE}; + const written = + note === undefined || version === undefined + ? $(await createFile(changeOf(run), {parentId: null, name, content: kept})) + : $(await writeFile(changeOf(run), {fileId: note.id, ifVersion: version, content: kept})); + const said = note === undefined ? `Wrote the new note “${title}”.` : `Wrote “${title}”. The version before is kept.`; + return [said, `Id: ${written.id}`, `Version: ${written.head?.id ?? ''}`].join('\n'); + }); + +const forgetSchema = z.object({id: z.string().min(1)}); + +/** memory_forget: a note put in the trash, which the person can take it out of. */ +export const runMemoryForget: NativeToolRunner = (run) => + Do(async ($): Promise => { + const {id} = $(read(forgetSchema, 'memory_forget', 'id', run.params)); + const file = $(await requireFile(run.connection.id, id)); + if (file.folder || file.parentId !== null) { + return $(Err(ApiErr.notFound('note', id, 'notes_list lists them.'))); + } + const trashed = $(await trashFile(changeOf(run), id)); + return `Forgot “${titleOf(trashed.name)}”. It is in the trash, where the person can take it back.`; + }); diff --git a/packages/api/src/native/sandbox/exec.test.ts b/packages/api/src/native/sandbox/exec.test.ts index e241c33e..d1c69b41 100644 --- a/packages/api/src/native/sandbox/exec.test.ts +++ b/packages/api/src/native/sandbox/exec.test.ts @@ -45,6 +45,11 @@ const wakeSandbox = mock(async () => Ok(sandbox)); mock.module('./machines', () => ({requireBackend, wakeSandbox})); +type Secret = {name: string; value: string}; +const secretsFor = mock(async (): Promise> => Ok({given: [], masked: []})); + +mock.module('./secrets', () => ({secretsFor})); + const signedIn = {agentId: 'agent-1', orgId: 'org-1', ownerUserId: 'user-1', providerId: 'claude', name: 'Claude', orgSlug: 'org-1', experiments: []}; const caller = {agent: signedIn, via: 'mcp' as const, taskId: 'task-1'}; const connection = {id: 'sandboxes-1'} as never; @@ -58,6 +63,7 @@ beforeEach(() => { mock.clearAllMocks(); sandbox.papVersion = 'v2'; exec.mockImplementation(async () => Ok(done)); + secretsFor.mockImplementation(async () => Ok({given: [], masked: []})); mockEnv.AUTH_SECRET = 'test-auth-secret'; mockEnv.APP_URL = 'https://app.example.com'; }); @@ -78,6 +84,31 @@ describe('runSandboxCommand', () => { expect(left).toBeLessThanOrEqual(91); }); + test('with secrets, the command is given each by its name, and what it writes shows each by its name', async () => { + const key = {name: 'API_KEY', value: 'sk-test-123'}; + secretsFor.mockImplementation(async () => Ok({given: [key], masked: [key]})); + exec.mockImplementation(async () => Ok({...done, stdout: 'key is sk-test-123\n'})); + const answer = (await run({secrets: ['API_KEY']})).unwrap(); + expect(exec.mock.calls.at(-1)?.[1].env).toEqual({API_KEY: 'sk-test-123'}); + expect(answer).toContain('key is [secret API_KEY]'); + expect(answer).not.toContain('sk-test-123'); + }); + + test('without secrets, the command is given none, and what it writes still shows each the agent may use by its name', async () => { + secretsFor.mockImplementation(async () => Ok({given: [], masked: [{name: 'API_KEY', value: 'sk-test-123'}]})); + exec.mockImplementation(async () => Ok({...done, stdout: 'API_KEY=sk-test-123\n'})); + const answer = (await run({command: 'cat env.txt'})).unwrap(); + expect(exec.mock.calls.at(-1)?.[1].env).toBeUndefined(); + expect(answer).toContain('API_KEY=[secret API_KEY]'); + expect(answer).not.toContain('sk-test-123'); + }); + + test('a secret no vault lets the agent use fails the call, and nothing is run', async () => { + secretsFor.mockImplementation(async () => Err(ApiErr.validationError('No vault lets you use its secrets'))); + expect((await run({secrets: ['API_KEY']})).isErr()).toBe(true); + expect(exec).not.toHaveBeenCalled(); + }); + test('without pap, no environment at all', async () => { await run({}); await run({pap: false}); diff --git a/packages/api/src/native/sandbox/exec.ts b/packages/api/src/native/sandbox/exec.ts index 29214a4e..3198207d 100644 --- a/packages/api/src/native/sandbox/exec.ts +++ b/packages/api/src/native/sandbox/exec.ts @@ -12,6 +12,8 @@ import type {NativeToolRunner} from '../tool'; import {holdForTask} from './lease'; import {requireBackend, wakeSandbox} from './machines'; import {ensurePap, withPapOnPath} from './pap'; +import {maskSecrets, secretEnv} from './secret-values'; +import {secretsFor} from './secrets'; /** * The console, `sandbox_exec`: a command run in a sandbox of the connection's for the caller's @@ -22,7 +24,10 @@ import {ensurePap, withPapOnPath} from './pap'; * the `pap` CLI on its PATH, installed first where it isn't this server's (pap.ts); without it, no * credential and nothing installed. The activity log has the command as the agent gave it. The * token is signed once the sandbox is woken and pap installed, so it lasts as long as the command - * may. + * may. With `secrets`, it is given the vaults' secrets named, as environment variables + * (secrets.ts); what any command writes back has the values of every secret the agent may use + * shown by their names, so one isn't read by accident. The log has the names alone, as the agent + * gave them. */ const paramsSchema = z.object({ @@ -32,6 +37,7 @@ const paramsSchema = z.object({ cwd: z.string().optional(), timeout: z.number().positive().max(SANDBOX_EXEC_MAX_SECONDS).optional(), pap: z.boolean().optional(), + secrets: z.array(z.string().min(1)).max(50).optional(), }); // How much of each stream the model is given; the gate cuts the whole answer further. @@ -65,9 +71,12 @@ export const runSandboxCommand: NativeToolRunner = ({caller, connection, params} Do(async ($): Promise => { const parsed = parseSchema(paramsSchema, params); if (parsed.isErr()) { - return $(Err(ApiErr.validationError(`sandbox_exec takes sandbox, command, and stdin, cwd, timeout and pap where wanted: ${parsed.error.kind === 'parse_error' ? parsed.error.message : ''}`))); + return $( + Err(ApiErr.validationError(`sandbox_exec takes sandbox, command, and stdin, cwd, timeout, pap and secrets where wanted: ${parsed.error.kind === 'parse_error' ? parsed.error.message : ''}`)), + ); } - const {sandbox: sandboxId, command, stdin, cwd, timeout = SANDBOX_EXEC_DEFAULT_SECONDS, pap = false} = parsed.value; + const {sandbox: sandboxId, command, stdin, cwd, timeout = SANDBOX_EXEC_DEFAULT_SECONDS, pap = false, secrets: asked = []} = parsed.value; + const {given: secrets, masked} = $(await secretsFor(caller, asked)); const config = pap ? $(requireCliTokenConfig()) : null; const bundle = pap ? $(await papBundle()) : null; const backend = $(await requireBackend()); @@ -78,8 +87,10 @@ export const runSandboxCommand: NativeToolRunner = ({caller, connection, params} $(await ensurePap(backend, running, bundle)); } const claims = {agentId: caller.agent.agentId, orgId: caller.agent.orgId, ownerUserId: caller.agent.ownerUserId, taskId: caller.taskId, sandboxId: running.id, connectionId: connection.id}; - const sent = config === null ? {command} : {command: withPapOnPath(command), env: cliCommandEnv(config, claims, timeout)}; + const given = secretEnv(secrets); + const plain = secrets.length === 0 ? {command} : {command, env: given}; + const sent = config === null ? plain : {command: withPapOnPath(command), env: {...given, ...cliCommandEnv(config, claims, timeout)}}; const output = $(await backend.exec(running.backendRef, {...sent, stdin, cwd, timeoutMs: Math.round(timeout * 1000)})); $(await touchSandbox(running.id)); - return describeOutput(output, timeout); + return describeOutput({...output, stdout: maskSecrets(output.stdout, masked), stderr: maskSecrets(output.stderr, masked)}, timeout); }); diff --git a/packages/api/src/native/sandbox/secret-values.test.ts b/packages/api/src/native/sandbox/secret-values.test.ts new file mode 100644 index 00000000..e32c03fb --- /dev/null +++ b/packages/api/src/native/sandbox/secret-values.test.ts @@ -0,0 +1,59 @@ +import {describe, expect, test} from 'bun:test'; + +import {maskSecrets, pickSecret, secretEnv} from './secret-values'; + +const own = {id: 'vault-1', integrationId: 'vault', account: 'Acme', shared: false, actions: ['useSecrets'], name: null, signInNeeded: false}; +const work = {...own, id: 'vault-2', name: 'Work', shared: true}; + +describe('pickSecret', () => { + test('finds a name one vault has', () => { + const held = [{name: 'API_KEY', value: 'sk-one', vault: own}]; + expect(pickSecret(held, 'API_KEY').unwrap()).toEqual({name: 'API_KEY', value: 'sk-one'}); + }); + + test('asks which vault where two have the name, and takes one named by its name or id', () => { + const held = [ + {name: 'API_KEY', value: 'sk-one', vault: own}, + {name: 'API_KEY', value: 'sk-two', vault: work}, + ]; + expect(pickSecret(held, 'API_KEY').isErr()).toBe(true); + expect(pickSecret(held, 'Work/API_KEY').unwrap().value).toBe('sk-two'); + expect(pickSecret(held, 'vault-1/API_KEY').unwrap().value).toBe('sk-one'); + expect(pickSecret(held, 'Vault/API_KEY').unwrap().value).toBe('sk-one'); + }); + + test('a name no vault has is not found', () => { + expect(pickSecret([], 'MISSING').unwrapErr().kind).toBe('not_found'); + }); +}); + +describe('maskSecrets', () => { + test('shows each value as its name, the longer first', () => { + const secrets = [ + {name: 'SHORT', value: 'abcd'}, + {name: 'LONG', value: 'abcdefgh'}, + ]; + expect(maskSecrets('key=abcdefgh and abcd', secrets)).toBe('key=[secret LONG] and [secret SHORT]'); + }); + + test('never takes a name already shown for a value', () => { + const secrets = [ + {name: 'OPENAI_API_KEY', value: 'sk-long-key-123'}, + {name: 'PROVIDER', value: 'OPENAI'}, + ]; + expect(maskSecrets('sk-long-key-123 from OPENAI', secrets)).toBe('[secret OPENAI_API_KEY] from [secret PROVIDER]'); + }); + + test('finds a value as it is, whatever it has in it', () => { + const secrets = [{name: 'PASSWORD', value: 'a.b*c(d)[e]$/-'}]; + expect(maskSecrets('pw: a.b*c(d)[e]$/- and axbxc', secrets)).toBe('pw: [secret PASSWORD] and axbxc'); + }); + + test('leaves values too short to tell apart as they are', () => { + expect(maskSecrets('a b c', [{name: 'TINY', value: 'b'}])).toBe('a b c'); + }); +}); + +test('secretEnv gives each secret by its name', () => { + expect(secretEnv([{name: 'API_KEY', value: 'sk-one'}])).toEqual({API_KEY: 'sk-one'}); +}); diff --git a/packages/api/src/native/sandbox/secret-values.ts b/packages/api/src/native/sandbox/secret-values.ts new file mode 100644 index 00000000..f6daaf99 --- /dev/null +++ b/packages/api/src/native/sandbox/secret-values.ts @@ -0,0 +1,66 @@ +import {Err, Ok, type Result} from 'ts-results-es'; + +import {ApiErr, type ApiError} from '@proxy/utils'; +import type {AgentConnection} from '@proxy/contracts/agent-side'; + +/** + * Secrets as a sandbox command is given them (secrets.ts finds them): the one a name asks for, + * the environment they make, and what the command wrote with each value shown as its name. + */ + +/** A secret as a command is given it. */ +export type GivenSecret = {name: string; value: string}; + +/** A secret of a vault the agent may use the secrets of. */ +export type HeldSecret = GivenSecret & {vault: AgentConnection}; + +// Whether the vault is the one a name was asked for in: by its id, or by what it is called, the +// person's own being called Vault. +function vaultCalled(vault: AgentConnection, called: string): boolean { + return vault.id === called || vault.name === called || (vault.name === null && called.toLowerCase() === 'vault'); +} + +/** The secret a name asks for, among those held: the one vault that has it, or the one named, as Work/OPENAI_API_KEY. */ +export function pickSecret(held: HeldSecret[], asked: string): Result { + const slash = asked.lastIndexOf('/'); + const name = slash === -1 ? asked : asked.slice(slash + 1); + const vault = slash === -1 ? null : asked.slice(0, slash); + const found = held.filter((secret) => secret.name === name && (vault === null || vaultCalled(secret.vault, vault))); + if (found.length > 1) { + return Err(ApiErr.validationError(`${name} is in more than one vault: ask for it as ${found.map((secret) => `${secret.vault.id}/${name}`).join(' or ')}`)); + } + const [only] = found; + if (!only) { + return Err(ApiErr.notFound('secret', asked, 'secrets_list, in a vault you may use the secrets of, lists them.')); + } + return Ok({name: only.name, value: only.value}); +} + +// Values shorter than this are left as they are in what a command writes: a word that short is +// more likely to be anything else. +const MASKED_FROM = 4; + +// A value as a pattern matching it as it is, whatever it has in it. +function escaped(value: string): string { + return value.replace(/[\\^$.*+?()[\]{}|/-]/g, '\\$&'); +} + +/** + * What a command wrote, each secret's value in it shown as [secret NAME]: all in one pass, the + * longest first where values overlap, so one inside another is never half shown and a name already + * shown is never mistaken for a value. + */ +export function maskSecrets(text: string, secrets: GivenSecret[]): string { + const masked = secrets.filter((secret) => secret.value.length >= MASKED_FROM).toSorted((a, b) => b.value.length - a.value.length); + if (masked.length === 0) { + return text; + } + const names = new Map(masked.map((secret) => [secret.value, secret.name])); + const pattern = new RegExp(masked.map((secret) => escaped(secret.value)).join('|'), 'g'); + return text.replace(pattern, (value) => `[secret ${names.get(value) ?? ''}]`); +} + +/** The secrets as environment variables, by their names. */ +export function secretEnv(secrets: GivenSecret[]): Record { + return Object.fromEntries(secrets.map((secret) => [secret.name, secret.value])); +} diff --git a/packages/api/src/native/sandbox/secrets.test.ts b/packages/api/src/native/sandbox/secrets.test.ts new file mode 100644 index 00000000..b41f950f --- /dev/null +++ b/packages/api/src/native/sandbox/secrets.test.ts @@ -0,0 +1,69 @@ +import {beforeEach, describe, expect, mock, test} from 'bun:test'; +import {Ok} from 'ts-results-es'; + +const vault = (id: string, name: string | null, actions: string[]) => ({id, integrationId: 'vault', account: 'Acme', shared: false, actions, name, signInNeeded: false}); + +const listAgentConnections = mock(); +mock.module('../../agent-side/tools', () => ({listAgentConnections})); + +const held: Record> = { + 'vault-1': [ + {name: 'API_KEY', value: 'sk-one'}, + {name: 'DB_URL', value: 'postgres://db'}, + ], + 'vault-2': [ + {name: 'WORK_TOKEN', value: 'tok-two'}, + {name: 'DB_URL', value: 'postgres://work'}, + ], + 'vault-3': [{name: 'HIDDEN', value: 'never-used'}], +}; +const listSecrets = mock(async (id: string) => Ok(held[id] ?? [])); +mock.module('../vault/connector', () => ({listSecrets})); + +const signedIn = {agentId: 'agent-1', orgId: 'org-1', ownerUserId: 'user-1', providerId: 'claude', name: 'Claude', orgSlug: 'org-1', experiments: []}; +const caller = {agent: signedIn, via: 'mcp' as const, taskId: 'task-1'}; + +beforeEach(() => { + mock.clearAllMocks(); + listAgentConnections.mockResolvedValue( + Ok({ + agent: {id: 'agent-1', providerId: 'claude', name: 'Claude'}, + connections: [vault('vault-1', null, ['readEntries', 'useSecrets']), vault('vault-2', 'Work', ['readEntries', 'useSecrets']), vault('vault-3', 'Other', ['readEntries'])], + }), + ); +}); + +describe('secretsFor', () => { + test('gives the command those asked for, and masks every secret of each vault the agent may use the secrets of', async () => { + const {secretsFor} = await import('./secrets'); + const {given, masked} = (await secretsFor(caller, ['API_KEY'])).unwrap(); + + expect(given).toEqual([{name: 'API_KEY', value: 'sk-one'}]); + expect(masked.map((secret) => secret.name).sort()).toEqual(['API_KEY', 'DB_URL', 'DB_URL', 'WORK_TOKEN']); + expect(listSecrets).not.toHaveBeenCalledWith('vault-3'); + }); + + test('asked for none, gives none and still masks them', async () => { + const {secretsFor} = await import('./secrets'); + const {given, masked} = (await secretsFor(caller, [])).unwrap(); + + expect(given).toEqual([]); + expect(masked).toHaveLength(4); + }); + + test('with no vault whose secrets it may use, a command asking for none runs as it is, and one asking for some is refused', async () => { + listAgentConnections.mockResolvedValue(Ok({agent: {id: 'agent-1', providerId: 'claude', name: 'Claude'}, connections: [vault('vault-3', 'Other', ['readEntries'])]})); + const {secretsFor} = await import('./secrets'); + + expect((await secretsFor(caller, [])).unwrap()).toEqual({given: [], masked: []}); + expect((await secretsFor(caller, ['API_KEY'])).unwrapErr().kind).toBe('validation_error'); + expect(listSecrets).not.toHaveBeenCalled(); + }); + + test('refuses one name asked for from two vaults, since a command is given one variable of it', async () => { + const {secretsFor} = await import('./secrets'); + + expect((await secretsFor(caller, ['Vault/DB_URL', 'Work/DB_URL'])).unwrapErr().kind).toBe('validation_error'); + expect((await secretsFor(caller, ['Work/DB_URL'])).unwrap().given).toEqual([{name: 'DB_URL', value: 'postgres://work'}]); + }); +}); diff --git a/packages/api/src/native/sandbox/secrets.ts b/packages/api/src/native/sandbox/secrets.ts new file mode 100644 index 00000000..b19798f0 --- /dev/null +++ b/packages/api/src/native/sandbox/secrets.ts @@ -0,0 +1,44 @@ +import {Err, type Result} from 'ts-results-es'; + +import {ApiErr, type ApiError, Do} from '@proxy/utils'; +import {VAULT_INTEGRATION_ID} from '@proxy/integrations'; + +import type {TaskCaller} from '../../agent-side/tools'; +import {listSecrets} from '../vault/connector'; +import {type GivenSecret, type HeldSecret, pickSecret} from './secret-values'; + +/** + * The secrets of a sandbox command: those it is given as environment variables, by the names the + * agent asked for, and those shown by their names wherever what it writes has their values, + * every secret of the vaults the agent may use the secrets of, asked for or not. + */ +export type CommandSecrets = {given: GivenSecret[]; masked: GivenSecret[]}; + +/** + * The vaults' secrets for a sandbox command, from the vaults the agent has Use secrets on. What a + * command is given it can read, and send anywhere, which the permission says: masking what it + * writes back (secret-values.ts) keeps a value out of the agent's answers by accident, as when a + * command prints its environment or a file one wrote before, not from an agent set on reading it. + * Masked on every call, since a value one command wrote to a file another may print. + */ +export function secretsFor(caller: TaskCaller, asked: string[]): Promise> { + return Do(async ($) => { + // Read when asked for: the agent side runs every tool, this one among them, so importing it + // as this file loads would load the whole of it with any sandbox module. + const {listAgentConnections} = await import('../../agent-side/tools'); + const {connections} = $(await listAgentConnections(caller.agent)); + const vaults = connections.filter((connection) => connection.integrationId === VAULT_INTEGRATION_ID && connection.actions.includes('useSecrets')); + if (vaults.length === 0 && asked.length > 0) { + return $(Err(ApiErr.validationError('No vault lets you use its secrets: the person turns on Use secrets for one on its page.'))); + } + const lists = await Promise.all(vaults.map(async (vault) => (await listSecrets(vault.id)).map((secrets) => secrets.map((secret): HeldSecret => ({...secret, vault}))))); + const held = lists.flatMap((list) => $(list)); + const given = [...new Set(asked)].map((name) => $(pickSecret(held, name))); + // Each is given as the environment variable of its name, which one command has only one of. + const twice = given.find((secret, index) => given.findIndex((other) => other.name === secret.name) !== index); + if (twice) { + return $(Err(ApiErr.validationError(`${twice.name} is asked for from more than one vault: a command is given one ${twice.name}, so ask for one of them`))); + } + return {given, masked: held.map(({name, value}) => ({name, value}))}; + }); +} diff --git a/packages/api/src/native/vault/connector.test.ts b/packages/api/src/native/vault/connector.test.ts index 1fea1ff2..9473d1cf 100644 --- a/packages/api/src/native/vault/connector.test.ts +++ b/packages/api/src/native/vault/connector.test.ts @@ -1,6 +1,7 @@ import {beforeEach, describe, expect, mock, test} from 'bun:test'; -import {Ok} from 'ts-results-es'; +import {Ok, type Result} from 'ts-results-es'; +import type {ApiError} from '@proxy/utils'; import {findCollection, findIntegration, type Collection} from '@proxy/integrations'; mock.module('../../utils/env', () => ({env: {ENCRYPTION_KEY: Buffer.alloc(32, 7).toString('base64')}})); @@ -126,3 +127,48 @@ describe('vaultConnector', () => { expect(result.unwrapErr().kind).toBe('internal_error'); }); }); + +describe('a vault’s secrets', () => { + function secrets(): Collection { + const integration = findIntegration('vault'); + const found = integration && findCollection(integration, 'secrets'); + if (!found) { + throw new Error('No secrets collection'); + } + return found; + } + + test('keep a value without the spaces and line breaks pasted around it, and refuse one that is only those', async () => { + const {vaultConnector} = await import('./connector'); + const kept = {...target, collection: secrets()}; + listVaultEntries.mockResolvedValue(Ok([])); + + const created = await vaultConnector.create(kept, {name: 'API_KEY', value: ' sk-test-123 \n', note: ''}); + expect(created.unwrap().values).toEqual({name: 'API_KEY', value: 'sk-test-123', note: ''}); + expect((await vaultConnector.create(kept, {name: 'API_KEY', value: ' \n', note: ''})).unwrapErr().kind).toBe('validation_error'); + }); + + test('refuse a name another secret of the vault has, as they are written, and let a secret keep its own', async () => { + const {vaultConnector, encryptValues} = await import('./connector'); + const kept = {...target, collection: secrets()}; + const others = [{id: 'rec-2', values: encryptValues({name: 'API_KEY', value: 'sk-other', note: ''}).unwrap(), updatedAt}]; + createVaultEntry.mockImplementation((_collection: unknown, values: string, check?: (rows: typeof others) => Result) => + Promise.resolve(check ? check(others).map(() => ({id: 'rec-1', values, updatedAt})) : Ok({id: 'rec-1', values, updatedAt})), + ); + + expect((await vaultConnector.create(kept, {name: 'API_KEY', value: 'sk-new', note: ''})).unwrapErr().kind).toBe('conflict'); + expect((await vaultConnector.create(kept, {name: 'OTHER_KEY', value: 'sk-new', note: ''})).isOk()).toBe(true); + }); + + test('are listed for a command without those that can’t be read', async () => { + const {listSecrets, encryptValues} = await import('./connector'); + listVaultEntries.mockResolvedValue( + Ok([ + {id: 'rec-1', values: encryptValues({name: 'API_KEY', value: 'sk-one', note: ''}).unwrap(), updatedAt}, + {id: 'rec-2', values: 'v1.not.encrypted.here', updatedAt}, + ]), + ); + + expect((await listSecrets('vault-1')).unwrap()).toEqual([{name: 'API_KEY', value: 'sk-one'}]); + }); +}); diff --git a/packages/api/src/native/vault/connector.ts b/packages/api/src/native/vault/connector.ts index 14cba62a..4d655697 100644 --- a/packages/api/src/native/vault/connector.ts +++ b/packages/api/src/native/vault/connector.ts @@ -2,17 +2,23 @@ import {Err, Ok, Result} from 'ts-results-es'; import {z} from 'zod'; import {ApiErr, type ApiError, Do, parseSchema, requirePresent} from '@proxy/utils'; -import {createVaultEntry, deleteVaultEntry, getVaultEntry, listVaultEntries, updateVaultEntry, type VaultEntryRow} from '@proxy/db/vault'; +import {SECRET_NAME_PATTERN, VAULT_SECRETS_COLLECTION_ID} from '@proxy/integrations'; +import {createVaultEntry, deleteVaultEntry, getVaultEntry, listVaultEntries, updateVaultEntry, type VaultCollection, type VaultEntriesCheck, type VaultEntryRow} from '@proxy/db/vault'; +import {log} from '../../observability/log'; import {decryptSecret, encryptSecret} from '../../utils/secret-crypto'; import {requireFirstPage, type DataRecord, type RecordStore, type RecordTarget, type RecordValues} from '../../records/connector'; const storedValuesSchema = z.record(z.string(), z.string()); -function vaultCollection(target: RecordTarget) { +function vaultCollection(target: RecordTarget): VaultCollection { return {connectionId: target.connection.id, collectionId: target.collection.id}; } +function isSecrets(target: RecordTarget): boolean { + return target.collection.id === VAULT_SECRETS_COLLECTION_ID; +} + export function encryptValues(values: RecordValues): Result { return encryptSecret(JSON.stringify(values)); } @@ -42,16 +48,86 @@ function toRecord(row: VaultEntryRow): Result { return decryptValues(row.values).map((values) => ({id: row.id, values, updatedAt: row.updatedAt.toISOString()})); } -/** The vault lives in Personal Agent Proxy: each entry's title, type and content are stored as encrypted JSON. */ +function listRecords(collection: VaultCollection): Promise> { + return Do(async ($) => { + const rows = $(await listVaultEntries(collection)); + return rows.map((row) => $(toRecord(row))); + }); +} + +/** + * A vault's secrets, each by its name and value, as a sandbox command is given them + * (native/sandbox/secrets.ts). One that can't be read is left out and logged rather than failing + * the rest: its value can't be given to a command, nor found in what one writes. + */ +export function listSecrets(connectionId: string): Promise, ApiError>> { + return Do(async ($) => { + const rows = $(await listVaultEntries({connectionId, collectionId: VAULT_SECRETS_COLLECTION_ID})); + return rows.flatMap((row) => { + const values = decryptValues(row.values); + if (values.isErr()) { + log.warn('A vault secret could not be read', {connectionId, recordId: row.id, errorKind: values.error.kind}); + return []; + } + return [{name: values.value.name ?? '', value: values.value.value ?? ''}]; + }); + }); +} + +// A secret needs a name a command's environment can have and a value, kept without the spaces and +// line breaks around it, which a paste brings along and a command's output may leave off, so that +// masking finds the value as printed (secret-values.ts). +function requireSecret(values: RecordValues): Result { + const name = (values.name ?? '').trim(); + if (!SECRET_NAME_PATTERN.test(name)) { + return Err(ApiErr.validationError('A secret’s name is an environment variable’s: letters, digits and _, not starting with a digit, as OPENAI_API_KEY')); + } + const value = (values.value ?? '').trim(); + if (value === '') { + return Err(ApiErr.validationError('A secret needs a value')); + } + return Ok({name, value, note: values.note ?? ''}); +} + +// No other secret of the vault has the name: checked as the secret is written, with the vault's +// other writes of secrets held off (@proxy/db/vault), so two at once can't both take it. +function nameFree(name: string): VaultEntriesCheck { + return (others) => { + const taken = others.some((other) => decryptValues(other.values).mapOr(false, (values) => values.name === name)); + if (taken) { + return Err(ApiErr.conflict(`This vault has a secret called ${name} already`)); + } + return Ok(undefined); + }; +} + +// What a write keeps, and what it checks of the collection's others as it writes: an entry with +// its type, one new needing something written in it; or a secret as it has to be, its name the +// vault's only one. +function written(target: RecordTarget, values: RecordValues, isNew: boolean): Result<{kept: RecordValues; check?: VaultEntriesCheck}, ApiError> { + if (isSecrets(target)) { + return requireSecret(values).map((kept) => ({kept, check: nameFree(kept.name ?? '')})); + } + if (isNew) { + return requireWritten(values).map(() => ({kept: withType(values)})); + } + return Ok({kept: withType(values)}); +} + +/** + * The vault lives in Personal Agent Proxy: each entry's title, type and content, and each secret's + * name, value and note, are stored as encrypted JSON. A search reads every field but those never + * given to an agent, a secret's value. + */ export const vaultConnector = { // Few enough to search in memory, after decrypting, and to list on one page. list: (target, query) => Do(async ($) => { $(requireFirstPage(query)); - const rows = $(await listVaultEntries(vaultCollection(target))); - const records = rows.map((row) => $(toRecord(row))); + const records = $(await listRecords(vaultCollection(target))); const search = query.search?.toLowerCase(); - const matching = search ? records.filter((record) => Object.values(record.values).some((value) => value.toLowerCase().includes(search))) : records; + const searched = target.collection.fields.filter((field) => !field.secret).map((field) => field.key); + const matching = search ? records.filter((record) => searched.some((key) => (record.values[key] ?? '').toLowerCase().includes(search))) : records; return {records: matching, nextPage: null}; }), get: (target, recordId) => @@ -61,13 +137,14 @@ export const vaultConnector = { }), create: (target, values) => Do(async ($) => { - $(requireWritten(values)); - const row = $(await createVaultEntry(vaultCollection(target), $(encryptValues(withType(values))))); + const {kept, check} = $(written(target, values, true)); + const row = $(await createVaultEntry(vaultCollection(target), $(encryptValues(kept)), check)); return $(toRecord(row)); }), update: (target, recordId, values) => Do(async ($) => { - const row = $(await updateVaultEntry(vaultCollection(target), recordId, $(encryptValues(withType(values))))); + const {kept, check} = $(written(target, values, false)); + const row = $(await updateVaultEntry(vaultCollection(target), recordId, $(encryptValues(kept)), check)); return $(toRecord(row)); }), remove: (target, recordId) => deleteVaultEntry(vaultCollection(target), recordId), diff --git a/packages/api/src/native/vault/integration.ts b/packages/api/src/native/vault/integration.ts index d74e7a6b..fd832a50 100644 --- a/packages/api/src/native/vault/integration.ts +++ b/packages/api/src/native/vault/integration.ts @@ -4,5 +4,5 @@ import type {ApiIntegration} from '../../connections/integration'; /** The vault, in Personal Agent Proxy itself: always there, never connected or disconnected. */ export const VAULT_INTEGRATION: ApiIntegration = { id: 'vault', - connectors: {entries: vaultConnector}, + connectors: {entries: vaultConnector, secrets: vaultConnector}, }; diff --git a/packages/api/src/orgs/invitation-link.test.ts b/packages/api/src/orgs/invitation-link.test.ts index 5119e7cc..f3df92cf 100644 --- a/packages/api/src/orgs/invitation-link.test.ts +++ b/packages/api/src/orgs/invitation-link.test.ts @@ -70,6 +70,7 @@ describe('handleAcceptInvitationRoute', () => { {integrationId: 'vault', defaults: ['readEntries', 'writeEntries']}, {integrationId: 'chat', defaults: [], builtInGrants: ['readThreads', 'readAlerts', 'cancelAlerts']}, {integrationId: 'files', defaults: ['readFiles', 'createFiles', 'editFiles', 'trashFiles']}, + {integrationId: 'memory', defaults: ['readMemory', 'writeMemory']}, ], }); expect(result.unwrap()).toEqual({orgId: 'org-2', orgSlug: 'acme'}); diff --git a/packages/api/src/orgs/provision.test.ts b/packages/api/src/orgs/provision.test.ts index 58736c61..bb1de426 100644 --- a/packages/api/src/orgs/provision.test.ts +++ b/packages/api/src/orgs/provision.test.ts @@ -24,12 +24,13 @@ describe('planPersonalOrgIdentity', () => { }); describe('the starter connections', () => { - it('are a vault of the member’s own, the owner’s as anyone’s, which agents read and write by default, their Chat, which only the built-in agent is given, and their Files, which agents may do everything with; the vaults, the Chats, the sandboxes and the files are named after the organization', () => { + it('are a vault of the member’s own, the owner’s as anyone’s, which agents read and write by default, their Chat, which only the built-in agent is given, and their Files and Memory, which agents may do everything with; the vaults, the Chats, the sandboxes, the files and the memories are named after the organization', () => { expect(MEMBER_CONNECTIONS).toEqual([ {integrationId: 'vault', defaults: ['readEntries', 'writeEntries']}, {integrationId: 'chat', defaults: [], builtInGrants: ['readThreads', 'readAlerts', 'cancelAlerts']}, {integrationId: 'files', defaults: ['readFiles', 'createFiles', 'editFiles', 'trashFiles']}, + {integrationId: 'memory', defaults: ['readMemory', 'writeMemory']}, ]); - expect(NAMED_AFTER_ORGANIZATION).toEqual(['vault', 'chat', 'sandbox', 'files']); + expect(NAMED_AFTER_ORGANIZATION).toEqual(['vault', 'chat', 'sandbox', 'files', 'memory']); }); }); diff --git a/packages/api/src/orgs/route.test.ts b/packages/api/src/orgs/route.test.ts index 5b28b5ff..7c50a897 100644 --- a/packages/api/src/orgs/route.test.ts +++ b/packages/api/src/orgs/route.test.ts @@ -174,7 +174,7 @@ describe('handleRenameOrgRoute', () => { const asMember = await handleRenameOrgRoute(makeRequest({}, {name: 'Mine now'})); expect(renameOrganization).toHaveBeenCalledTimes(1); - expect(renameOrganization).toHaveBeenCalledWith('org-2', 'Acme Inc', ['vault', 'chat', 'sandbox', 'files']); + expect(renameOrganization).toHaveBeenCalledWith('org-2', 'Acme Inc', ['vault', 'chat', 'sandbox', 'files', 'memory']); expect(asMember.unwrapErr().kind).toBe('forbidden'); }); }); diff --git a/packages/api/src/orgs/starter-connections.ts b/packages/api/src/orgs/starter-connections.ts index a8e9efbd..ef638f9c 100644 --- a/packages/api/src/orgs/starter-connections.ts +++ b/packages/api/src/orgs/starter-connections.ts @@ -1,4 +1,14 @@ -import {CHAT_BUILT_IN_ACTIONS, CHAT_INTEGRATION_ID, FILES_DEFAULT_ACTIONS, FILES_INTEGRATION_ID, SANDBOX_INTEGRATION_ID, VAULT_DEFAULT_ACTIONS, VAULT_INTEGRATION_ID} from '@proxy/integrations'; +import { + CHAT_BUILT_IN_ACTIONS, + CHAT_INTEGRATION_ID, + FILES_DEFAULT_ACTIONS, + FILES_INTEGRATION_ID, + MEMORY_DEFAULT_ACTIONS, + MEMORY_INTEGRATION_ID, + SANDBOX_INTEGRATION_ID, + VAULT_DEFAULT_ACTIONS, + VAULT_INTEGRATION_ID, +} from '@proxy/integrations'; import type {StarterConnection} from '@proxy/db/organization'; /** @@ -7,16 +17,18 @@ import type {StarterConnection} from '@proxy/db/organization'; * should know about them, which nobody else there uses; and their Chat, their threads on the Chat * page as records, which no agent may do anything with by default but the organization's built-in * agent, given everything in its own settings, where the member turns it off as for any agent: - * what was said in a thread may have come from a connection another agent was never given; and - * their Files, a drive of their own, which agents may do everything with by default, since nothing - * done to a drive is lost, each write keeping the version before and the trash what was put in it. + * what was said in a thread may have come from a connection another agent was never given; their + * Files, a drive of their own; and their Memory, the notes all their agents share, kept as a + * drive's files are. Agents may do everything with a drive and a memory by default, since nothing + * done to either is lost, each write keeping the version before and the trash what was put in it. * A vault or a drive to share is one they make beside it (connections/route.ts). */ export const MEMBER_CONNECTIONS: StarterConnection[] = [ {integrationId: VAULT_INTEGRATION_ID, defaults: VAULT_DEFAULT_ACTIONS}, {integrationId: CHAT_INTEGRATION_ID, defaults: [], builtInGrants: CHAT_BUILT_IN_ACTIONS}, {integrationId: FILES_INTEGRATION_ID, defaults: FILES_DEFAULT_ACTIONS}, + {integrationId: MEMORY_INTEGRATION_ID, defaults: MEMORY_DEFAULT_ACTIONS}, ]; -/** The integrations whose connections are called by the organization's name: the vaults, the Chats and the Files, and the Sandboxes made later (native/sandbox/connections.ts). */ -export const NAMED_AFTER_ORGANIZATION: string[] = [VAULT_INTEGRATION_ID, CHAT_INTEGRATION_ID, SANDBOX_INTEGRATION_ID, FILES_INTEGRATION_ID]; +/** The integrations whose connections are called by the organization's name: the vaults, the Chats, the Files and the Memory, and the Sandboxes made later (native/sandbox/connections.ts). */ +export const NAMED_AFTER_ORGANIZATION: string[] = [VAULT_INTEGRATION_ID, CHAT_INTEGRATION_ID, SANDBOX_INTEGRATION_ID, FILES_INTEGRATION_ID, MEMORY_INTEGRATION_ID]; diff --git a/packages/api/src/server/create-api-router.ts b/packages/api/src/server/create-api-router.ts index 73ceeca6..ce6886f5 100644 --- a/packages/api/src/server/create-api-router.ts +++ b/packages/api/src/server/create-api-router.ts @@ -86,6 +86,7 @@ import { handleUploadFileRoute, handleWriteFileRoute, } from '../native/files/route'; +import {handleMemoryRoute} from '../native/memory/route'; import {chatFiles} from '../native/files/chat'; import {handleBlobGetRoute, handleBlobPutRoute} from '../blobs/route'; import {handleCliCheckPushRoute, handleCliListFilesRoute, handleCliPullFileRoute, handleCliPushFileRoute} from '../native/files/cli'; @@ -232,6 +233,9 @@ export function createApiRouter(): express.Router { org.post(`${files}/:fileId/trash`, withAuthResult('Trash file route', handleTrashFileRoute)); org.post(`${files}/:fileId/untrash`, withAuthResult('Untrash file route', handleUntrashFileRoute)); org.post(`${files}/:fileId/restore`, withAuthResult('Restore file version route', handleRestoreFileRoute)); + // A member's memory, for its connection's page (native/memory/route.ts); its notes are changed + // through the drive's routes above, being kept as a drive's files are. + org.get('/connections/:connectionId/memory', withAuthResult('Memory route', handleMemoryRoute)); // A Google connection's history of its files in Drive, for its page (records/google-history-route.ts). const driveHistory = '/connections/:connectionId/drive-history'; diff --git a/packages/contracts/src/memory.ts b/packages/contracts/src/memory.ts new file mode 100644 index 00000000..25fde3f2 --- /dev/null +++ b/packages/contracts/src/memory.ts @@ -0,0 +1,32 @@ +import {z} from 'zod'; + +import {fileMakerSchema} from './files'; + +/** + * A member's memory, as the person reads it on its connection's page + * (`/api/orgs/:org/connections/:connectionId/memory`): its notes, each whole, with the agents + * that wrote it. A note's versions, writing one, giving an earlier one back and putting one in the + * trash are the drive's routes (files.ts), its notes being kept as a drive's files are. + */ + +export const memoryNoteSchema = z.object({ + id: z.string(), + title: z.string(), + /** Its first line, which every thread is given in the index. */ + summary: z.string(), + content: z.string(), + /** The version it holds now, which a write over it names. */ + version: z.string(), + modifiedAt: z.string(), + /** The agents that wrote it, the latest first; none where only the person did. */ + makers: z.array(fileMakerSchema), + /** About you: the note every thread is given whole. */ + about: z.boolean(), +}); + +export type MemoryNote = z.infer; + +/** `GET memory`: the notes, the latest changed first. */ +export const memorySchema = z.object({notes: z.array(memoryNoteSchema)}); + +export type Memory = z.infer; diff --git a/packages/db/prisma/migrations/v077_make_memory_with_memberships/migration.sql b/packages/db/prisma/migrations/v077_make_memory_with_memberships/migration.sql new file mode 100644 index 00000000..cba82042 --- /dev/null +++ b/packages/db/prisma/migrations/v077_make_memory_with_memberships/migration.sql @@ -0,0 +1,19 @@ +-- Every member has their own Memory from the start, as they have a vault, a Chat and a drive: the +-- notes all their agents share, kept as a drive's files are. Those of members who joined before +-- are made here, called by the organization's name, agents allowed to read and write them by +-- default. + +WITH made AS ( + INSERT INTO "Connection" ("id", "orgId", "integrationId", "account", "ownerUserId", "createdAt", "updatedAt") + SELECT gen_random_uuid()::text, m."orgId", 'memory', o."name", m."userId", now(), now() + FROM "OrgMember" AS m JOIN "Organization" AS o ON o."id" = m."orgId" + WHERE NOT EXISTS ( + SELECT 1 FROM "Connection" AS c + WHERE c."orgId" = m."orgId" AND c."integrationId" = 'memory' AND c."ownerUserId" = m."userId" AND c."name" IS NULL + ) + RETURNING "id" +) +INSERT INTO "ConnectionDefault" ("id", "connectionId", "actionId", "createdAt", "updatedAt") +SELECT gen_random_uuid()::text, made."id", d."actionId", now(), now() +FROM made +CROSS JOIN (VALUES ('readMemory'), ('writeMemory')) AS d("actionId"); diff --git a/packages/db/src/files.ts b/packages/db/src/files.ts index 8e620e8c..88388b10 100644 --- a/packages/db/src/files.ts +++ b/packages/db/src/files.ts @@ -593,6 +593,47 @@ export function searchFiles( }); } +/** A file at the top of a drive with what it holds now and the blob with its bytes. */ +export type TopFile = FileNodeRow & {head: StoredVersionRow & {blob: FileBlobRow}}; + +/** + * The files at the top of a drive, outside the trash, each with what it holds now and the blob + * with its bytes, the latest changed first, at most `take`: for a drive read whole, as a member's + * memory is (api native/memory). Folders, and files with nothing in them, are left out. + */ +export function listTopFiles( + connectionId: string, + take: number, +): Promise> { + return wrapDb(async () => { + const nodes = await db.fileNode.findMany({ + where: { + connectionId, + parentId: null, + folder: false, + trashedAt: null, + headVersionId: {not: null}, + }, + select: nodeSelect, + orderBy: [{updatedAt: 'desc'}, {id: 'asc'}], + take, + }); + const ids = nodes.flatMap((node) => (node.headVersionId === null ? [] : [node.headVersionId])); + const versions = await db.fileVersion.findMany({ + where: {id: {in: ids}}, + select: {...versionSelect, blob: {select: blobSelect}}, + }); + const byId = new Map(versions.map((version) => [version.id, version])); + return nodes.flatMap((node) => { + const head = node.headVersionId === null ? undefined : byId.get(node.headVersionId); + if (!head || head.blob === null || !isStored(head)) { + return []; + } + return [{...node, head: {...head, blob: head.blob}}]; + }); + }); +} + /** What was put in the trash, each by itself, last trashed first, with where it was. */ export function listTrash(connectionId: string): Promise> { return wrapDb(async () => { diff --git a/packages/db/src/vault.test.ts b/packages/db/src/vault.test.ts new file mode 100644 index 00000000..aee50501 --- /dev/null +++ b/packages/db/src/vault.test.ts @@ -0,0 +1,103 @@ +import {afterAll, beforeAll, describe, expect, test} from 'bun:test'; +import {Err, Ok, type Result} from 'ts-results-es'; + +import {ApiErr, type ApiError} from '@proxy/utils'; + +import {db} from '.'; +import { + createVaultEntry, + listVaultEntries, + updateVaultEntry, + type VaultCollection, + type VaultEntriesCheck, +} from './vault'; + +// A vault's checked writes, against the local database: run with it up (`bun run dev`) and the +// environment loaded, `bun --env-file=../../.env test src/vault.test.ts` from this package. +// Without DATABASE_URL, as `bun run test` runs, there is nothing to run against, and this is +// skipped. Everything made here is one organization's, deleted at the end. The values stand for +// encrypted ones: this package never reads them, only a check does. +const databaseUrl = process.env.DATABASE_URL; + +function unwrap(result: Result): T { + if (result.isErr()) { + throw new Error(JSON.stringify(result.error)); + } + return result.value; +} + +// No other row holds the value, as the api checks a secret's name. +function valueFree(value: string): VaultEntriesCheck { + return (rows) => { + if (rows.some((row) => row.values === value)) { + return Err(ApiErr.conflict(`${value} is taken`)); + } + return Ok(undefined); + }; +} + +describe.skipIf(!databaseUrl)('vault, against the database', () => { + const stamp = `${Date.now()}-${process.pid}`; + let userId = ''; + let orgId = ''; + let collection: VaultCollection = {connectionId: '', collectionId: 'secrets'}; + + beforeAll(async () => { + const user = await db.user.create({ + data: {email: `vault-test-${stamp}@example.test`, name: 'Dana'}, + }); + userId = user.id; + const org = await db.organization.create({ + data: {name: 'Vault test', slug: `vault-test-${stamp}`, ownerUserId: userId}, + }); + orgId = org.id; + const connection = await db.connection.create({ + data: {orgId, integrationId: 'vault', ownerUserId: userId, account: 'Vault test'}, + }); + collection = {connectionId: connection.id, collectionId: 'secrets'}; + }); + + afterAll(async () => { + if (orgId !== '') { + await db.organization.delete({where: {id: orgId}}); + } + if (userId !== '') { + await db.user.delete({where: {id: userId}}); + } + }); + + test('checked writes at once are checked one after the other, so only one takes a value', async () => { + const results = await Promise.all( + Array.from({length: 5}, () => createVaultEntry(collection, 'API_KEY', valueFree('API_KEY'))), + ); + + expect(results.filter((result) => result.isOk())).toHaveLength(1); + expect( + results.filter((result) => result.isErr()).map((result) => result.unwrapErr().kind), + ).toEqual(['conflict', 'conflict', 'conflict', 'conflict']); + expect(unwrap(await listVaultEntries(collection))).toHaveLength(1); + }); + + test('an update is checked against the others alone, and a refused one changes nothing', async () => { + const own = unwrap(await createVaultEntry(collection, 'OWN_KEY', valueFree('OWN_KEY'))); + + expect( + unwrap(await updateVaultEntry(collection, own.id, 'OWN_KEY', valueFree('OWN_KEY'))).id, + ).toBe(own.id); + expect( + (await updateVaultEntry(collection, own.id, 'API_KEY', valueFree('API_KEY'))).unwrapErr() + .kind, + ).toBe('conflict'); + expect( + unwrap(await listVaultEntries(collection)) + .map((row) => row.values) + .sort(), + ).toEqual(['API_KEY', 'OWN_KEY']); + }); + + test('an update of an entry not in the collection is not found', async () => { + const result = await updateVaultEntry(collection, 'missing', 'X', valueFree('X')); + + expect(result.unwrapErr().kind).toBe('not_found'); + }); +}); diff --git a/packages/db/src/vault.ts b/packages/db/src/vault.ts index e9aa4a2f..65a638ba 100644 --- a/packages/db/src/vault.ts +++ b/packages/db/src/vault.ts @@ -1,6 +1,7 @@ +import type {Prisma} from '@prisma/client'; import {Err, type Result} from 'ts-results-es'; -import {ApiErr, type ApiError, Do, requirePresent, wrapDb} from '@proxy/utils'; +import {ApiErr, type ApiError, Do, wrapDb} from '@proxy/utils'; import {db} from '.'; @@ -33,12 +34,46 @@ export async function getVaultEntry( ); } +/** + * What a write checks of the collection's entries as they are when it writes: the others' rows, + * read with the collection's other checked writes held off until this one is done, so two at once + * never both pass. An error stops the write. + */ +export type VaultEntriesCheck = (rows: VaultEntryRow[]) => Result; + +type Tx = Prisma.TransactionClient; + +// Every checked write of the collection, one after the other: a lock on a key made of the +// collection, held until the transaction ends, as the collection has no row of its own to take. +async function checkEntries( + tx: Tx, + collection: VaultCollection, + check: VaultEntriesCheck, + recordId: string | null, +): Promise { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`vault:${collection.connectionId}:${collection.collectionId}`}::text, 0))`; + const rows = await tx.vaultEntry.findMany({ + where: {...collection, ...(recordId === null ? {} : {id: {not: recordId}})}, + select: vaultEntrySelect, + }); + const checked = check(rows); + if (checked.isErr()) { + throw checked.error; + } +} + export async function createVaultEntry( collection: VaultCollection, values: string, + check?: VaultEntriesCheck, ): Promise> { return wrapDb(() => - db.vaultEntry.create({data: {...collection, values}, select: vaultEntrySelect}), + db.$transaction(async (tx) => { + if (check) { + await checkEntries(tx, collection, check, null); + } + return tx.vaultEntry.create({data: {...collection, values}, select: vaultEntrySelect}); + }), ); } @@ -47,20 +82,30 @@ export async function updateVaultEntry( collection: VaultCollection, recordId: string, values: string, + check?: VaultEntriesCheck, ): Promise> { - return Do(async ($) => { - const {count} = $( - await wrapDb(() => - db.vaultEntry.updateMany({where: {...collection, id: recordId}, data: {values}}), - ), - ); - if (count === 0) { - return $(Err(ApiErr.notFound('record', recordId))); - } - - const row = $(await getVaultEntry(collection, recordId)); - return $(requirePresent(row, ApiErr.notFound('record', recordId))); - }); + return wrapDb(() => + db.$transaction(async (tx) => { + if (check) { + await checkEntries(tx, collection, check, recordId); + } + const {count} = await tx.vaultEntry.updateMany({ + where: {...collection, id: recordId}, + data: {values}, + }); + if (count === 0) { + throw ApiErr.notFound('record', recordId); + } + const row = await tx.vaultEntry.findFirst({ + where: {...collection, id: recordId}, + select: vaultEntrySelect, + }); + if (!row) { + throw ApiErr.notFound('record', recordId); + } + return row; + }), + ); } /** Fails with not_found when the entry isn't in the collection. */ @@ -78,14 +123,14 @@ export async function deleteVaultEntry( }); } -// A record from before the vault had one collection: an address, a payment card or a note, until -// the api turns it into an entry as it starts. +// A record from before the vault had its entries: an address, a payment card or a note, until the +// api turns it into an entry as it starts. A secret is the vault's own, as an entry is. export type OldVaultRecord = {id: string; collectionId: string; values: string}; export async function listOldVaultRecords(): Promise> { return wrapDb(() => db.vaultEntry.findMany({ - where: {collectionId: {not: 'entries'}}, + where: {collectionId: {notIn: ['entries', 'secrets']}}, select: {id: true, collectionId: true, values: true}, }), ); diff --git a/packages/integrations/src/catalog.ts b/packages/integrations/src/catalog.ts index abc6909f..e13d1c30 100644 --- a/packages/integrations/src/catalog.ts +++ b/packages/integrations/src/catalog.ts @@ -2063,6 +2063,12 @@ const plaid: Integration = { ], }; +/** The vault's secrets, beside its entries. */ +export const VAULT_SECRETS_COLLECTION_ID = 'secrets'; + +/** What a secret's name has to be: an environment variable's, as OPENAI_API_KEY. */ +export const SECRET_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/; + // What a vault entry's value is, so a row shows it as such and an agent knows what it holds. export const VAULT_ENTRY_TYPES = ['Text', 'Address', 'Phone number', 'Email', 'Link', 'Date']; @@ -2072,11 +2078,17 @@ export const VAULT_ENTRY_TYPES = ['Text', 'Address', 'Phone number', 'Email', 'L const vault: Integration = { id: VAULT_INTEGRATION_ID, name: 'Vault', - description: 'What agents should know, kept in Personal Agent Proxy', + description: + 'What your agents may know about you, and the secrets they may use, kept in Personal Agent Proxy', native: true, - made: {one: 'vault', holds: 'entries'}, + made: {one: 'vault', holds: 'entries and secrets'}, actions: [ - {id: 'readEntries', label: 'Read entries', description: 'List and open entries', risk: 'low'}, + { + id: 'readEntries', + label: 'Read entries', + description: 'List and open entries, and see which secrets there are', + risk: 'low', + }, { id: 'writeEntries', label: 'Edit entries', @@ -2084,6 +2096,22 @@ const vault: Integration = { risk: 'medium', requires: 'readEntries', }, + { + id: 'writeSecrets', + label: 'Save secrets', + description: + 'Add, replace and delete secrets, such as a key it made, without reading any back', + risk: 'medium', + requires: 'readEntries', + }, + { + id: 'useSecrets', + label: 'Use secrets', + description: + 'Give secrets to sandbox commands as environment variables. A command can read what it is given and send it anywhere', + risk: 'high', + requires: 'readEntries', + }, ], collections: [ { @@ -2101,12 +2129,32 @@ const vault: Integration = { {key: 'content', label: 'Content', type: 'longtext'}, ], }, + // Secrets, such as API keys, by the environment variable a command is given each as: an + // agent sees a secret's name and note, never its value, which only the person reads, on the + // vault's page. Agents with Use secrets have them given to a sandbox command by name + // (native/sandbox/secrets.ts); with Save secrets, add, replace and delete them, as a key + // they made, without ever reading one back. + { + id: VAULT_SECRETS_COLLECTION_ID, + name: 'Secrets', + singular: 'secret', + titleField: 'name', + summaryField: 'note', + read: 'readEntries', + writes: {create: 'writeSecrets', update: 'writeSecrets', delete: 'writeSecrets'}, + searchHint: 'Matches the words in the name or the note, in any case.', + fields: [ + {key: 'name', label: 'Name', type: 'text'}, + {key: 'value', label: 'Value', type: 'text', secret: true}, + {key: 'note', label: 'Note', type: 'longtext'}, + ], + }, ], }; // What agents may do with a vault by default, a member's own and any they make: read it, and -// keep what they learn there, unless told otherwise. -export const VAULT_DEFAULT_ACTIONS: string[] = vault.actions.map((action) => action.id); +// keep what they learn there, unless told otherwise. Its secrets are the person's to hand out. +export const VAULT_DEFAULT_ACTIONS: string[] = ['readEntries', 'writeEntries']; export const SANDBOX_INTEGRATION_ID = 'sandbox'; @@ -2225,6 +2273,12 @@ const sandbox: Integration = { type: 'boolean', description: 'Lets the command use pap, to call your connections from code', }, + secrets: { + type: 'array', + items: {type: 'string'}, + description: + 'Vault secrets to give the command as environment variables, by name, as OPENAI_API_KEY, or as Vault name/NAME where two vaults have it. Where any command prints a secret’s value, it is shown as [secret NAME]', + }, }, required: ['sandbox', 'command'], }, @@ -2612,6 +2666,97 @@ const mcp: Integration = { collections: [], }; +export const MEMORY_INTEGRATION_ID = 'memory'; + +/** The note every thread is given whole: what the person's agents know about them. */ +export const MEMORY_ABOUT_TITLE = 'About you'; + +/** How long "About you" may be, in characters, and any other note. */ +export const MEMORY_ABOUT_CHARACTERS = 3_000; +export const MEMORY_NOTE_CHARACTERS = 20_000; + +/** How long a note's first line, its summary in the index every thread is given, may be. */ +export const MEMORY_SUMMARY_CHARACTERS = 200; + +// Memory lives in Personal Agent Proxy itself: notes the person's agents keep for next time, one +// memory of each member's own, which all their agents share. Kept as a drive is (FileNode, +// FileVersion, FileChange), so every version of a note stays and who wrote each is known, but an +// integration of its own: agents read and write notes, not files, and the person reads them on +// its page. Every thread is given "About you" whole and an index of the other notes, each by its +// first line, its summary (mcp/tools.ts); the rest is read when needed. +const memory: Integration = { + id: MEMORY_INTEGRATION_ID, + name: 'Memory', + description: 'What your agents learn as they work, kept for next time', + native: true, + actions: [ + {id: 'readMemory', label: 'Read memory', description: 'Read and search the notes', risk: 'low'}, + { + id: 'writeMemory', + label: 'Write memory', + description: 'Write, change and forget notes; every version before is kept', + risk: 'medium', + requires: 'readMemory', + }, + ], + collections: [ + { + id: 'notes', + name: 'Notes', + singular: 'note', + titleField: 'title', + summaryField: 'summary', + searchHint: 'Words in a note’s title or text, in any case.', + read: 'readMemory', + // Written by memory_write, which names who wrote it and the version it read. + writes: {}, + fields: [ + {key: 'title', label: 'Title', type: 'text', system: true}, + {key: 'summary', label: 'Summary', type: 'text', system: true}, + {key: 'content', label: 'Content', type: 'longtext', system: true}, + // What memory_write has to name to write over it. + {key: 'version', label: 'Version', type: 'text', system: true}, + {key: 'writtenBy', label: 'Written by', type: 'text', system: true}, + {key: 'modified', label: 'Modified', type: 'datetime', system: true}, + ], + }, + ], + tools: [ + { + name: 'memory_write', + title: 'Write note', + description: `Writes a note called title. Its first line is its summary, which every thread is given in the index; the rest is read when needed. A new title makes a note; to change one, give the version notes_get answered with: where it changed since, the write is refused, and you read it again. Every version before is kept. “${MEMORY_ABOUT_TITLE}” is the note every thread is given whole: what is true of the person, at most ${MEMORY_ABOUT_CHARACTERS} characters; any other, at most ${MEMORY_NOTE_CHARACTERS}.`, + action: 'writeMemory', + inputSchema: { + type: 'object', + properties: { + title: {type: 'string', description: 'The note’s title, as Screenshots of the web app'}, + content: {type: 'string', description: 'The whole note, its summary on the first line'}, + version: { + type: 'string', + description: 'The version you read, to change a note that is there', + }, + }, + required: ['title', 'content'], + }, + }, + { + name: 'memory_forget', + title: 'Forget note', + description: `Forgets a note that is wrong or no longer of use: it goes to the trash, where the person can take it back for ${FILES_TRASH_DAYS} days.`, + action: 'writeMemory', + inputSchema: { + type: 'object', + properties: {id: {type: 'string', description: 'The note’s id'}}, + required: ['id'], + }, + }, + ], +}; + +/** What agents may do with a member's memory by default: read it and write it, since nothing written there is lost. */ +export const MEMORY_DEFAULT_ACTIONS: string[] = memory.actions.map((action) => action.id); + export const CHAT_INTEGRATION_ID = 'chat'; /** Where a thread stands, as its record says it and a list of threads is narrowed by: the Chat page's own words, Watching for one done but with alerts that come to it, and Archived for one the person archived, which the Chat page's list leaves out. */ @@ -2726,6 +2871,7 @@ export const INTEGRATIONS: Integration[] = [ mysql, sandbox, files, + memory, chat, mcp, ]; diff --git a/packages/integrations/src/index.ts b/packages/integrations/src/index.ts index a87c3acd..63014bf9 100644 --- a/packages/integrations/src/index.ts +++ b/packages/integrations/src/index.ts @@ -13,12 +13,20 @@ export { INTEGRATIONS, LINEAR_PRIORITIES, LINEAR_STATUS_TYPES, + MEMORY_ABOUT_CHARACTERS, + MEMORY_ABOUT_TITLE, + MEMORY_DEFAULT_ACTIONS, + MEMORY_INTEGRATION_ID, + MEMORY_NOTE_CHARACTERS, + MEMORY_SUMMARY_CHARACTERS, SANDBOX_EXEC_DEFAULT_SECONDS, SANDBOX_EXEC_MAX_SECONDS, SANDBOX_INTEGRATION_ID, + SECRET_NAME_PATTERN, VAULT_DEFAULT_ACTIONS, VAULT_ENTRY_TYPES, VAULT_INTEGRATION_ID, + VAULT_SECRETS_COLLECTION_ID, } from './catalog'; export {allowedTools, findTool, integrationTools, toolName} from './tools'; export type { diff --git a/packages/integrations/src/tools.test.ts b/packages/integrations/src/tools.test.ts index c782e4bf..aeeb41ab 100644 --- a/packages/integrations/src/tools.test.ts +++ b/packages/integrations/src/tools.test.ts @@ -710,6 +710,11 @@ describe("an integration's own tools", () => { 'entries_create', 'entries_update', 'entries_delete', + 'secrets_list', + 'secrets_get', + 'secrets_create', + 'secrets_update', + 'secrets_delete', 'entries_count', 'entries_purge', ]); diff --git a/packages/integrations/src/types.ts b/packages/integrations/src/types.ts index 758d5d2d..538d4f6f 100644 --- a/packages/integrations/src/types.ts +++ b/packages/integrations/src/types.ts @@ -15,6 +15,9 @@ export type Field = { // The action writing it needs beyond the collection's write: creating or editing a record where // it holds anything, before the write or after it, as an event's guests need Invite guests. action?: string; + // Never given to an agent, as a vault's secret's value: the person reads it on the connection's + // page, and agents only use it where an action lets them. + secret?: true; }; // One thing an agent can be allowed to do with a connection, set on its own: Read, Archive, Send. @@ -119,6 +122,7 @@ export type IntegrationId = | 'plaid' | 'sandbox' | 'files' + | 'memory' | 'chat'; // A tool of Personal Agent Proxy's own, with params of its own shape, as running a command in a diff --git a/packages/web/src/client/memory-client.ts b/packages/web/src/client/memory-client.ts new file mode 100644 index 00000000..3681e261 --- /dev/null +++ b/packages/web/src/client/memory-client.ts @@ -0,0 +1,9 @@ +import {memorySchema} from '@proxy/contracts/memory'; +import {apiRequest, orgApi} from '@/client/request'; + +// A member's memory, on its connection's page: its notes, each whole. What the person does to one +// goes through the drive's routes (files-client.ts), its notes being kept as a drive's files are. + +export function getMemory(org: string, connectionId: string) { + return apiRequest('GET', `${orgApi(org)}/connections/${connectionId}/memory`, memorySchema); +} diff --git a/packages/web/src/components/file-browser.tsx b/packages/web/src/components/file-browser.tsx index 53533e3a..8e5bdb7c 100644 --- a/packages/web/src/components/file-browser.tsx +++ b/packages/web/src/components/file-browser.tsx @@ -24,6 +24,7 @@ import { UploadIcon, } from 'lucide-react'; import {Fragment, useEffect, useRef, useState, type DragEvent} from 'react'; +import {createPortal} from 'react-dom'; import {Link, useNavigate} from 'react-router'; import { createFolder, @@ -108,7 +109,7 @@ function MakerMark({maker}: {maker: FileMaker}) { // The agents that made what a file holds, the latest in front, overlapping, the first few drawn // and the rest counted, named under the pointer; nothing for a file only members made. -function Makers({makers}: {makers: FileMaker[]}) { +export function Makers({makers}: {makers: FileMaker[]}) { if (makers.length === 0) { return null; } @@ -551,6 +552,8 @@ type Props = { place: DrivePlace; list: FileList | null; shown: FileDetail | null; + // Where its search and buttons go, on the page's row of tabs (page-tabs.tsx). + toolbar: HTMLElement | null; }; // The Files part of a drive's page, the first of its connection's tabs: the folder the person is @@ -559,7 +562,7 @@ type Props = { // dropping files on the list, and a new folder. A file opens over its folder with its versions, // and a file or a folder is renamed, moved into another folder, or put in the trash from its // row's menu. The trash is a list of its own, each thing in it taken out again. -export function FileBrowser({connectionId, place, list, shown}: Props) { +export function FileBrowser({connectionId, place, list, shown, toolbar}: Props) { const org = useOrgSlug(); const navigate = useNavigate(); const reload = useReload(); @@ -601,10 +604,16 @@ export function FileBrowser({connectionId, place, list, shown}: Props) { return (
-
- - {!trash && list !== null && ( - + {(trash || (list?.trail.length ?? 0) > 0) && ( +
+ +
+ )} + {toolbar !== null && + !trash && + list !== null && + createPortal( + @@ -619,9 +628,9 @@ export function FileBrowser({connectionId, place, list, shown}: Props) { > {uploading > 0 ? : } - +
, + toolbar, )} -
{ + const response = await fetch(path, {credentials: 'same-origin'}); + return response.ok ? response.text() : ''; +} + +// What a version changed from the one before it, a line at a time. +function Changes({lines}: {lines: DiffLine[]}) { + if (lines.every((line) => line.kind === 'same')) { + return

No change to the text.

; + } + return ( +
+			{lines.map((line, index) => (
+				
+ + {line.kind === 'added' ? '+' : line.kind === 'removed' ? '−' : ' '} + + {line.text || ' '} +
+ ))} +
+ ); +} + +// A note's versions, newest first, each with who wrote it and when, what it changed from the one +// before, shown on asking, and giving it back. +function History({ + connectionId, + note, + versions, +}: { + connectionId: string; + note: MemoryNote; + versions: FileVersion[]; +}) { + const org = useOrgSlug(); + const [error, setError] = useState(null); + const apply = useApply(setError); + const [shown, setShown] = useState<{id: string; lines: DiffLine[]} | null>(null); + + const compare = async (index: number) => { + const version = versions[index]; + if (!version) { + return; + } + if (shown?.id === version.id) { + setShown(null); + return; + } + const before = versions[index + 1]; + const [now, then] = await Promise.all([ + versionText(fileContentPath(org, connectionId, note.id, version.id)), + before + ? versionText(fileContentPath(org, connectionId, note.id, before.id)) + : Promise.resolve(''), + ]); + setShown({id: version.id, lines: diffLines(then, now)}); + }; + + return ( +
+

History

+
    + {versions.map((version, index) => ( +
  • +
    + + + + + {formatAgo(version.at)} + + + {version.current && ( + + Current + + )} + + + void compare(index)} + > + + + {!version.current && ( + + void apply(restoreFileVersion(org, connectionId, note.id, version.id)) + } + > + + + )} + +
    + {shown?.id === version.id && } +
  • + ))} +
+ {error &&

{error}

} +
+ ); +} + +// A note opened: what it says, written over by the person, forgotten, and its history. +function NoteDialog({ + connectionId, + note, + onClose, +}: { + connectionId: string; + note: MemoryNote; + onClose: () => void; +}) { + const org = useOrgSlug(); + const [detail, setDetail] = useState(null); + const [editing, setEditing] = useState(null); + const [error, setError] = useState(null); + const apply = useApply(setError); + + useEffect(() => { + let left = false; + void getFile(org, connectionId, note.id).then((answer) => { + if (left) { + return; + } + if (answer.isErr()) { + setError(describeApiError(answer.error)); + return; + } + setDetail(answer.value); + }); + return () => { + left = true; + }; + }, [org, connectionId, note.id, note.version]); + + return ( + + + {note.title} + + {note.makers.length > 0 ? 'Written by your agents' : 'Written by you'} + + · changed {formatAgo(note.modifiedAt)} + + + {editing === null ? ( + <> +
+ setEditing(note.content)}> + + + void apply(trashFile(org, connectionId, note.id), onClose)} + > + + +
+
+ +
+ + ) : ( + <> +