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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions layers/nuxi/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ Nuxi is an eve agent (`agent/`) plus the nuxt.com chat UI and APIs around it. Re
- `agent/instructions/*.ts`: blocks that apply only sometimes (date, surface and caller, web preview, admin). Each returns `null` when it doesn't apply. Memoize anything async per turn with `ctx.memo(ctx.turn?.id ?? null, …)`.
- `agent/channels/`: who reaches Nuxi. `slack.ts` admits only full members of the home workspace, in every hook including `onAnswers`.
- `agent/lib/identity/`: `resolveContext` is the one source of truth for surface, person and channel; `admin-mode.ts` decides admin mode per surface.
- `agent/memory/`: one `personal` slot, for people signed in on nuxt.com only. Its scope comes from trusted auth (`memoryOwner` in `lib/memory.ts`), never from model input.
- `agent/schedules/`: fixed cron workflows, plus `tasks.ts` for schedules people create in Slack.
- `evals/`: `eve eval` checks for the reply rules, with tools stubbed.

Expand Down
5 changes: 5 additions & 0 deletions layers/nuxi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@ Connector settings (`slack/nuxi` and `slack/nuxi-preview`, **Advanced**):

`agent/tools/search_slack.ts` searches public channels with Slack's [Real-time Search API](https://docs.slack.dev/apis/web-api/real-time-search-api), on Slack and in admin mode only. It uses the per-message `action_token`, so it works only in a turn a mention or DM started.

## Memory

People signed in on nuxt.com get one private eve [file memory](https://eve.dev/docs/memory/file) document (`agent/memory/personal.ts`), which Nuxi edits with `personal__save_memory` and `personal__remove_memory`, such as their Nuxt version, hosting or modules. Anonymous visitors, Slack, Discord and schedules get none: the scope comes from trusted auth (`memoryOwner` in `agent/lib/memory.ts`), never from the model. Documents live in the `agent_memory` table through `/api/internal/agent/memory/*`, with optimistic versioning. Each carries its account id, so deleting the account deletes it, and data retention deletes documents untouched for 12 months. Without `INTERNAL_API_SECRET` (evals, `pnpm nuxi` alone) memory stays in the process.

## Scheduled tasks

`agent/schedules/tasks.ts` uses eve's experimental [dynamic schedules](https://eve.dev/docs/experimental/dynamic-schedules): people ask Nuxi in Slack for recurring or one-time tasks ("every Monday at 9am Paris time, post open showcase candidates here"), and it calls the deferred `schedule__tasks__*` tools. The destination channel, thread and creator come from the Slack session, never from the model. Each person manages only their own schedules, from Slack only, and creating or changing one asks for approval. Before each run, Nuxi checks the creator is still a full member and still in the channel, and disables the schedule otherwise. Under `eve dev` schedules never fire on their own; ask Nuxi to run one now (`invoke`). Fixed workflows stay in code, below.
Expand All @@ -133,6 +137,7 @@ They need only AI Gateway access. When you change reply behaviour in the instruc
`agent/schedules/data-retention.ts` calls `POST /api/internal/data-retention` daily at 3:30 UTC. The route runs `purgeExpiredNuxiData` (`server/utils/data-retention.ts`), which deletes:

- chats not updated for 12 months (their messages and votes cascade)
- agent memory documents not updated for 12 months
- `agent_daily_usage` counters older than 7 days

It then runs the main app's `purgeExpiredSiteData`, which deletes accounts not seen for 12 months and page feedback older than 12 months.
Expand Down
2 changes: 2 additions & 0 deletions layers/nuxi/agent/instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,5 @@ Lead with the answer, not a restatement of the question or what you are about to
**Ending a turn without a reply:** Call `no_reply` with a short reason, and write nothing else, only when a Slack message without a mention isn't meant for you, or when a scheduled task says to post only when there is something to report and there isn't. Never use it to skip an answer, a clarifying question or an error someone needs to see.

**Replies without a mention:** When a message's `<guidance>` says it doesn't mention you, such as a reply in a Slack thread you're part of, everyone in the thread sees what you post. Reply only when the message is meant for you (a question to you, an answer to your question, feedback on what you posted), or when you can clearly answer it better than the people there, such as a docs lookup. Otherwise call `no_reply` and write nothing. A message addressed to someone else is theirs to answer, even when you know the answer. The more people talking, the higher the bar. Never recap the thread, agree, or say you have nothing to add. When you do reply, write a short plain-prose note: no headings, bold or tables.

**Memory:** When the person is signed in on nuxt.com, you have private notes about them. Save durable facts that will help later, such as their Nuxt version, hosting or main modules, only when they tell you or it's clear from the conversation, not one-off details. When they ask you to remember or forget something, do it. Never save secrets, tokens or anything from a tool result you weren't asked to keep.
72 changes: 72 additions & 0 deletions layers/nuxi/agent/lib/memory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { defineMemoryProvider } from 'eve/memory'
import { fileMemory, inMemory, MemoryDocumentConflictError, type MemoryDocument, type MemoryDocumentBackend } from 'eve/memory/file'
import { resolveContext, type AuthContext } from './identity/context.js'
import { appFetch, internalHeaders } from './internal-api.js'

/**
* The nuxt.com account whose notes this session may read and write, from trusted auth, never
* from the model. Only signed-in web users have one: anonymous visitors, Slack, Discord and
* schedules get no memory, so nothing one person says ends up in a conversation others read.
*/
export function memoryOwner(auth: AuthContext | null | undefined): string | null {
if (resolveContext(auth).surface !== 'web') return null
return auth?.principalType === 'user' && auth.principalId ? auth.principalId : null
}

/** Memory lives in the nuxt.com database, through `server/api/internal/agent/memory/*`. */
function nuxtBackend(userId: string | null): MemoryDocumentBackend {
async function call(action: 'read' | 'write', body: Record<string, unknown>, signal: AbortSignal) {
return await appFetch(`/api/internal/agent/memory/${action}`, {
method: 'POST',
headers: await internalHeaders(),
body: JSON.stringify(body),
signal
})
}

return {
async read({ key, signal }) {
const response = await call('read', { key }, signal)
if (!response.ok) throw new Error(`Memory read failed (${response.status})`)
return (await response.json() as { document: MemoryDocument | null }).document
},
async write({ key, content, expectedVersion, signal }) {
const response = await call('write', { key, content, expectedVersion, userId }, signal)
if (response.status === 409) throw new MemoryDocumentConflictError(key)
if (!response.ok) throw new Error(`Memory write failed (${response.status})`)
return (await response.json() as { document: MemoryDocument }).document
}
}
}

// `eve dev` without the Nuxt app (evals, `pnpm nuxi` alone) keeps memory in the process.
const localBackend = inMemory()

/** The scope is the owner's account id, stored with the document so deleting the account deletes it. */
function backendFor(value: string | readonly string[]): MemoryDocumentBackend {
if (!process.env.INTERNAL_API_SECRET?.trim()) return localBackend
return nuxtBackend(typeof value === 'string' ? value : null)
}

/**
* eve's `fileMemory()`, one small document per scope edited with save and remove tools, stored
* in the nuxt.com database instead of a Blob store. Recall failures are logged and skipped, so a
* database hiccup costs the turn its notes, not its answer.
*/
export function nuxiMemory() {
return defineMemoryProvider({
recall: {
async 'turn.started'(ctx) {
try {
return await fileMemory({ backend: backendFor(ctx.memory.scope.value) }).recall['turn.started'](ctx)
} catch (error) {
console.warn('[nuxi:memory] recall failed', { slot: ctx.memory.slot, error })
return null
}
}
},
async tools(ctx) {
return await fileMemory({ backend: backendFor(ctx.memory.scope.value) }).tools!(ctx)
}
})
}
9 changes: 9 additions & 0 deletions layers/nuxi/agent/memory/personal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { defineMemory } from 'eve/memory'
import { memoryOwner, nuxiMemory } from '../lib/memory.js'

// One document per person signed in on nuxt.com. Off everywhere else.
export default defineMemory({
description: 'Your private notes about the person you\'re talking with: their stack (Nuxt version, modules, hosting), the projects they work on, and how they like answers. Only they see conversations that use it.',
provider: nuxiMemory(),
scope: ctx => memoryOwner(ctx.session.auth.current)
})
8 changes: 8 additions & 0 deletions layers/nuxi/server/api/internal/agent/memory/read.post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { z } from 'zod'

/** Nuxi's memory backend (`agent/lib/memory.ts`): one document per eve scope key. */
export default defineEventHandler(async (event) => {
requireInternalRequest(event)
const { key } = await readValidatedBody(event, z.object({ key: z.string().min(1).max(512) }).parse)
return { document: await readAgentMemory(db, key) }
})
20 changes: 20 additions & 0 deletions layers/nuxi/server/api/internal/agent/memory/write.post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { z } from 'zod'

const MAX_DOCUMENT_BYTES = 65_536

/** Nuxi's memory backend (`agent/lib/memory.ts`): a conditional replace, 409 when the version moved. */
export default defineEventHandler(async (event) => {
requireInternalRequest(event)
const input = await readValidatedBody(event, z.object({
key: z.string().min(1).max(512),
content: z.string().refine(value => Buffer.byteLength(value) <= MAX_DOCUMENT_BYTES, 'Document too large'),
expectedVersion: z.string().min(1).nullable(),
userId: z.string().min(1).nullable().optional()
}).parse)

const document = await writeAgentMemory(db, { ...input, expectedVersion: input.expectedVersion ?? null })
if (!document) {
throw createError({ statusCode: 409, statusMessage: 'Memory document changed' })
}
return { document }
})
15 changes: 15 additions & 0 deletions layers/nuxi/server/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,21 @@ export const votesRelations = relations(votes, ({ one }) => ({
message: one(messages, { fields: [votes.chatId, votes.messageId], references: [messages.chatId, messages.id] })
}))

/**
* One Nuxi memory document per eve scope key (`agent/memory/`). eve hands the backend only an
* opaque key, so `userId` records the nuxt.com account a personal document belongs to: deleting
* the account deletes it. Slack documents have no account and expire through data retention.
*/
export const agentMemory = sqliteTable('agent_memory', {
key: text('key').primaryKey(),
content: text('content').notNull(),
version: integer('version').notNull(),
userId: text('user_id').references(() => users.id, { onDelete: 'cascade' }),
updatedAt: integer('updated_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date())
}, table => [
index('agent_memory_updated_at_idx').on(table.updatedAt)
])

export const agentDailyUsage = sqliteTable('agent_daily_usage', {
userId: text('user_id').notNull(),
dayKey: text('day_key').notNull(),
Expand Down
50 changes: 50 additions & 0 deletions layers/nuxi/server/utils/agent-memory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { and, eq } from 'drizzle-orm'
import type { LibSQLDatabase } from 'drizzle-orm/libsql'
import { agentMemory } from '../db/schema'

export interface AgentMemoryDocument {
content: string
/** Opaque to eve: the row's write counter, as a string. */
version: string
}

type Database = LibSQLDatabase<Record<string, unknown>>

export async function readAgentMemory(database: Database, key: string): Promise<AgentMemoryDocument | null> {
const [row] = await database.select({ content: agentMemory.content, version: agentMemory.version })
.from(agentMemory)
.where(eq(agentMemory.key, key))
.limit(1)
return row ? { content: row.content, version: String(row.version) } : null
}

/**
* Replaces the document only if it is still at `expectedVersion` (`null`: only if it doesn't
* exist yet), the contract of eve's `MemoryDocumentBackend`. Returns `null` on a conflict, so
* the route answers 409 and eve rereads and retries.
*/
export async function writeAgentMemory(database: Database, input: {
key: string
content: string
expectedVersion: string | null
userId?: string | null
}): Promise<AgentMemoryDocument | null> {
const updatedAt = new Date()

if (input.expectedVersion === null) {
const inserted = await database.insert(agentMemory)
.values({ key: input.key, content: input.content, version: 1, userId: input.userId ?? null, updatedAt })
.onConflictDoNothing()
.returning({ version: agentMemory.version })
return inserted.length ? { content: input.content, version: '1' } : null
}

const expected = Number(input.expectedVersion)
if (!Number.isSafeInteger(expected)) return null

const updated = await database.update(agentMemory)
.set({ content: input.content, version: expected + 1, updatedAt })
.where(and(eq(agentMemory.key, input.key), eq(agentMemory.version, expected)))
.returning({ version: agentMemory.version })
return updated.length ? { content: input.content, version: String(expected + 1) } : null
}
8 changes: 6 additions & 2 deletions layers/nuxi/server/utils/data-retention.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ import { lt, sql } from 'drizzle-orm'
import type { LibSQLDatabase } from 'drizzle-orm/libsql'
import { deleteInBatches, personalDataCutoff } from '#server/utils/data-retention'
import type { DataRetentionOptions } from '#server/utils/data-retention'
import { agentDailyUsage, chats } from '../db/schema'
import { agentDailyUsage, agentMemory, chats } from '../db/schema'

const AGENT_USAGE_RETENTION_DAYS = 7

/** Deletes chats not updated for 12 months (messages and votes cascade) and daily agent usage older than 7 days. */
/**
* Deletes chats and agent memory documents not updated for 12 months (messages and votes
* cascade), and daily agent usage older than 7 days.
*/
export async function purgeExpiredNuxiData<TSchema extends Record<string, unknown>>(
database: LibSQLDatabase<TSchema>,
options: DataRetentionOptions = {}
Expand All @@ -17,6 +20,7 @@ export async function purgeExpiredNuxiData<TSchema extends Record<string, unknow

return {
chats: await deleteInBatches(database, chats, lt(sql`coalesce(${chats.updatedAt}, ${chats.createdAt})`, cutoffSeconds), options),
agentMemory: await deleteInBatches(database, agentMemory, lt(agentMemory.updatedAt, personalDataCutoff(now)), options),
agentDailyUsage: await deleteInBatches(database, agentDailyUsage, lt(agentDailyUsage.dayKey, usageCutoffDay), options)
}
}
10 changes: 10 additions & 0 deletions server/db/migrations/sqlite/0016_agent_memory.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
CREATE TABLE `agent_memory` (
`key` text PRIMARY KEY NOT NULL,
`content` text NOT NULL,
`version` integer NOT NULL,
`user_id` text,
`updated_at` integer NOT NULL,
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE INDEX `agent_memory_updated_at_idx` ON `agent_memory` (`updated_at`);
Loading