diff --git a/.env.example b/.env.example index af84c9a..c1cf215 100644 --- a/.env.example +++ b/.env.example @@ -31,3 +31,10 @@ PLOMPY_CODEX_BIN=codex # Explicit acknowledgement: OpenCode runs with service-account host permissions. # PLOMPY_OPENCODE_HOST_EXECUTION=allow PLOMPY_TASK_TIMEOUT_MS=1200000 + +# Optional personal assistant preview. Use a dedicated thread in the configured +# private owner forum, then choose the maximum age of missed reminders (1–1440 min). +# PLOMPY_ASSISTANT_THREAD_ID=555555555555555555 +# PLOMPY_ASSISTANT_TIME_ZONE=UTC +# PLOMPY_ASSISTANT_LOCALE=en +# PLOMPY_ASSISTANT_MAX_LATE_MINUTES=60 diff --git a/CHANGELOG.md b/CHANGELOG.md index bb30d85..62ca1b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 1.0.0-alpha.1 + +- Add the optional [personal assistant preview](docs/personal-assistant.md) with private notes, open tasks, and reminder questions that survive restart. +- Schedule, move and cancel one-time reminders in a dedicated owner thread. A separate delivery loop runs while the coding worker is busy. +- Record confirmed, failed, overdue and uncertain delivery attempts. The owner chooses a lateness window before enabling the assistant. +- Keep assistant data in its own versioned SQLite file. The coding engine continues to use schema 6. + ## 0.13.0 (2026-11-12): Local tools for your agent - Add an authenticated local MCP gateway for independently running Codex, Claude Code, OpenCode and compatible clients, without Discord or a second model account in the container. diff --git a/Dockerfile b/Dockerfile index d3b4c1b..82c97e1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -20,7 +20,7 @@ COPY packages/mcp-bridge/package.json packages/mcp-bridge/package-lock.json ./ RUN npm ci --omit=dev --ignore-scripts --no-audit --no-fund FROM node:26.13.0-bookworm-slim@sha256:add5c17c14752c54d2f3d519ec46a3815684d41c33f198bcb09fb998f7dcbf68 AS runtime -ARG VERSION=0.13.0 +ARG VERSION=1.0.0-alpha.1 ARG REVISION=unknown LABEL org.opencontainers.image.title="Plompy Engine" \ org.opencontainers.image.description="Self-hosted Discord agent engine with durable jobs and private Markdown memory" \ diff --git a/Dockerfile.local b/Dockerfile.local index a7b463d..6539efb 100644 --- a/Dockerfile.local +++ b/Dockerfile.local @@ -1,6 +1,6 @@ # syntax=docker/dockerfile:1 FROM node:26.13.0-bookworm-slim@sha256:add5c17c14752c54d2f3d519ec46a3815684d41c33f198bcb09fb998f7dcbf68 AS local-base -ARG VERSION=0.13.0 +ARG VERSION=1.0.0-alpha.1 ARG REVISION=unknown LABEL org.opencontainers.image.title="Plompy Local MCP" \ org.opencontainers.image.description="Local integration tools for an external MCP client" \ diff --git a/README.md b/README.md index e0b211c..17f90ec 100644 --- a/README.md +++ b/README.md @@ -82,9 +82,12 @@ integrations, and print the appropriate client configuration without embedding s - **Delivery and maintenance:** result receipts, transcript exports and scoped local Git commits have separate durable state. - **Deployment checks:** owner/forum authorization, local diagnostics, versioned migrations and verified state snapshots. -The public edition has **one global worker**. Work sessions yield between verified steps; -they do not interrupt a running step. Still-image input and supervised goals use Codex. -There is no built-in scheduler, publication broker or message-history catch-up after an outage. +The public edition has **one global worker** for coding agents. Work sessions yield between verified steps. +Still-image input and supervised goals use Codex. + +The [personal assistant preview](docs/personal-assistant.md) adds notes, tasks, follow-up +questions and one-time reminders in a dedicated private Discord thread. The reminder +scheduler runs independently of the coding worker. ## Quick start diff --git a/apps/discord-agent/package-lock.json b/apps/discord-agent/package-lock.json index b7a60c1..5afa548 100644 --- a/apps/discord-agent/package-lock.json +++ b/apps/discord-agent/package-lock.json @@ -1,13 +1,13 @@ { "name": "@plompy/discord-agent", - "version": "0.13.0", + "version": "1.0.0-alpha.1", "lockfileVersion": 3, "requires": true, "license": "MIT", "packages": { "": { "name": "@plompy/discord-agent", - "version": "0.13.0", + "version": "1.0.0-alpha.1", "license": "MIT", "dependencies": { "discord.js": "14.28.0", diff --git a/apps/discord-agent/package.json b/apps/discord-agent/package.json index b5dc1c6..2edb8ab 100644 --- a/apps/discord-agent/package.json +++ b/apps/discord-agent/package.json @@ -1,6 +1,6 @@ { "name": "@plompy/discord-agent", - "version": "0.13.0", + "version": "1.0.0-alpha.1", "private": true, "type": "module", "engines": { diff --git a/apps/discord-agent/src/assistant-delivery.ts b/apps/discord-agent/src/assistant-delivery.ts new file mode 100644 index 0000000..074177d --- /dev/null +++ b/apps/discord-agent/src/assistant-delivery.ts @@ -0,0 +1,146 @@ +import type { DeliveryClaim, AssistantStore } from "./assistant-store.js"; + +type DeliveryStore = Pick< + AssistantStore, + "claimDue" | "beginDelivery" | "finishDelivery" | "recoverDeliveries" +>; + +export type ReminderSendResult = + | { kind: "sent"; messageId: string } + | { kind: "retry"; retryAfterMs?: number } + | { kind: "failed" } + | { kind: "ambiguous" }; + +type SendReminder = ( + threadId: string, + content: string, +) => Promise; + +interface Options { + threadId: string; + locale: "en" | "pl"; + maxLatenessMs: number; + now?: () => number; + onError?: () => void; +} + +const POLL_MS = 5_000; +const FIRST_BACKOFF_MS = 15_000; +const MAX_ATTEMPTS = 3; +const MAX_PER_TICK = 4; +const MESSAGE_LIMIT = 1_800; + +function messageFor( + claim: DeliveryClaim, + locale: Options["locale"], + now: number, +): string { + const late = now - claim.dueAt >= 60_000; + const heading = + locale === "pl" + ? late + ? "Opóźnione przypomnienie" + : "Przypomnienie" + : late + ? "Delayed reminder" + : "Reminder"; + const due = new Intl.DateTimeFormat(locale === "pl" ? "pl-PL" : "en-GB", { + timeZone: claim.zone, + dateStyle: "long", + timeStyle: "short", + hourCycle: "h23", + }).format(claim.dueAt); + return `**${heading} ${claim.id}** · ${due} (${claim.zone})\n${claim.text}`; +} + +export class ReminderScheduler { + private timer: NodeJS.Timeout | undefined; + private inFlight: Promise | undefined; + private stopped = false; + private readonly now: () => number; + + constructor( + private readonly store: DeliveryStore, + private readonly send: SendReminder, + private readonly options: Options, + ) { + this.now = options.now ?? Date.now; + } + + start(): void { + if (this.timer || this.stopped) return; + this.store.recoverDeliveries(this.now()); + const poll = (): void => { + void this.tick().catch(() => this.options.onError?.()); + }; + this.timer = setInterval(poll, POLL_MS); + poll(); + } + + tick(): Promise { + if (this.inFlight) return this.inFlight; + if (this.stopped) return Promise.resolve(); + this.inFlight = Promise.resolve() + .then(() => this.deliverDue()) + .finally(() => { + this.inFlight = undefined; + }); + return this.inFlight; + } + + async stop(): Promise { + this.stopped = true; + clearInterval(this.timer); + this.timer = undefined; + await this.inFlight; + } + + private async deliverDue(): Promise { + for (let index = 0; index < MAX_PER_TICK && !this.stopped; index++) { + const now = this.now(); + const claim = this.store.claimDue(now, this.options.maxLatenessMs); + if (!claim) return; + const content = messageFor(claim, this.options.locale, now); + // Assignment alone does not authorize a send. Cancellation/rescheduling + // may have superseded the claim before this durable transition. + if (!this.store.beginDelivery(claim, this.now())) continue; + const result = await this.dispatch(content); + const finishedAt = this.now(); + if (result.kind !== "retry") { + this.store.finishDelivery(claim, result, finishedAt); + continue; + } + if (claim.attempt >= MAX_ATTEMPTS) { + this.store.finishDelivery(claim, { kind: "failed" }, finishedAt); + continue; + } + const backoff = FIRST_BACKOFF_MS * 2 ** (claim.attempt - 1); + const requested = result.retryAfterMs ?? 0; + const delay = Number.isFinite(requested) + ? Math.max(backoff, requested) + : backoff; + const retryAt = finishedAt + Math.ceil(delay); + // A definitive rejection still cannot be retried earlier than Discord + // allows, or later than the configured delivery window. + const canRetry = + Number.isFinite(new Date(retryAt).getTime()) && + retryAt <= claim.dueAt + this.options.maxLatenessMs; + this.store.finishDelivery( + claim, + canRetry ? { kind: "retry", retryAt } : { kind: "failed" }, + finishedAt, + ); + } + } + + private async dispatch(content: string): Promise { + if (content.length > MESSAGE_LIMIT) return { kind: "failed" }; + try { + return await this.send(this.options.threadId, content); + } catch { + // A rejected promise alone does not establish that Discord rejected the + // request. Only explicit, known pre-dispatch/rejection outcomes can retry. + return { kind: "ambiguous" }; + } + } +} diff --git a/apps/discord-agent/src/assistant-intent.ts b/apps/discord-agent/src/assistant-intent.ts new file mode 100644 index 0000000..0f33a9f --- /dev/null +++ b/apps/discord-agent/src/assistant-intent.ts @@ -0,0 +1,396 @@ +export type AssistantLocale = "en" | "pl"; + +export type AssistantIntent = + | { kind: "help" } + | { kind: "invalid" } + | { kind: "tasks" } + | { kind: "reminders" } + | { kind: "questions" } + | { kind: "note-add"; text: string } + | { kind: "task-add"; text: string } + | { kind: "notes"; query?: string } + | { kind: "task-done"; id?: string } + | { kind: "reminder-set"; text: string; dueAt: number } + | { kind: "reminder-move"; id?: string; dueAt: number } + | { kind: "reminder-cancel"; id: string } + | { kind: "question-cancel"; id: string } + | { kind: "reminder-question"; text: string; date?: string; id?: never } + | { kind: "reminder-question"; id?: string; date?: string; text?: never } + | { + kind: "reminder-answer"; + questionId?: string; + time: string; + date?: string; + }; + +interface ParseOptions { + now: number; + zone: string; + locale: AssistantLocale; +} + +const dayPattern = String.raw`(?:\d{4}-\d{2}-\d{2}|today|tomorrow|dzi[sś](?:iaj)?|jutro|pojutrze)`; +const timePattern = String.raw`\d{2}:\d{2}(?:\s+UTC[+-]\d{2}:\d{2})?`; +const relativePattern = String.raw`(?:za|in)\s+(\d{1,4})\s*(min(?:\.|ut(?:a|y|ę)?|utes?)?|m|hours?|h|godz(?:\.|in(?:ę|y|a)?)?)`; +const absolutePattern = String.raw`(?:(${dayPattern})(?:\s+(?:(?:o|at)\s+)?(${timePattern}))?|(?:(?:o|at)\s+)?(${timePattern}))`; +const absoluteTime = new RegExp(`^${absolutePattern}$`, "iu"); +const relativeTime = new RegExp(`^${relativePattern}$`, "iu"); +const leadingSchedule = new RegExp( + String.raw`^(${relativePattern}|${absolutePattern})(?=$|[\s,])`, + "iu", +); +const trailingSchedule = new RegExp( + String.raw`\s+(${relativePattern}|${absolutePattern})$`, + "iu", +); +const invalid: AssistantIntent = { kind: "invalid" }; +const help: AssistantIntent = { kind: "help" }; + +function localWallTime(ms: number, format: Intl.DateTimeFormat): string { + const parts = new Map( + format.formatToParts(ms).map(({ type, value }) => [type, value]), + ); + return `${parts.get("year")}-${parts.get("month")}-${parts.get("day")}T${parts.get("hour")}:${parts.get("minute")}:00.000Z`; +} + +function wallClock(zone: string): Intl.DateTimeFormat { + return new Intl.DateTimeFormat("en-CA-u-ca-iso8601-nu-latn", { + timeZone: zone, + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + hourCycle: "h23", + }); +} + +function isCalendarDate(date: string): boolean { + if (!/^[1-9]\d{3}-\d{2}-\d{2}$/.test(date)) return false; + const parsed = new Date(`${date}T00:00:00.000Z`); + return ( + Number.isFinite(parsed.getTime()) && parsed.toISOString().startsWith(date) + ); +} + +const clockTime = + /^([01]\d|2[0-3]):([0-5]\d)(?:\s+UTC([+-])([01]\d|2[0-3]):([0-5]\d))?$/i; + +export function localAssistantDate(now: number, zone: string): string { + return localWallTime(now, wallClock(zone)).slice(0, 10); +} + +export function formatAssistantTime( + ms: number, + zone: string, + locale: AssistantLocale, +): string { + const time = new Intl.DateTimeFormat(locale === "pl" ? "pl-PL" : "en-GB", { + timeZone: zone, + day: "numeric", + month: "long", + year: "numeric", + hour: "2-digit", + minute: "2-digit", + timeZoneName: "shortOffset", + hourCycle: "h23", + }).format(ms); + return `${time} (${zone})`; +} + +/** A local gap or fold requires a new answer unless a valid UTC offset selects the occurrence. */ +export function resolveAssistantTime( + date: string, + time: string, + zone: string, +): number | null { + if (!isCalendarDate(date)) return null; + const match = time.match(clockTime); + if (!match) return null; + const local = `${date}T${match[1]}:${match[2]}:00.000Z`; + const wall = Date.parse(local); + const format = wallClock(zone); + if (match[3]) { + const offset = (Number(match[4]) * 60 + Number(match[5])) * 60_000; + const instant = wall + (match[3] === "+" ? -offset : offset); + return localWallTime(instant, format) === local ? instant : null; + } + + // Sample both sides of nearby timezone changes. Validate candidates against the + // exact wall clock so forward jumps yield no match and backward jumps yield two. + const instants = new Set(); + for (const hours of [-36, -24, -12, 0, 12, 24, 36]) { + const sample = wall + hours * 3_600_000; + const offset = Date.parse(localWallTime(sample, format)) - sample; + const instant = wall - offset; + if (localWallTime(instant, format) === local) instants.add(instant); + } + return instants.size === 1 ? (instants.values().next().value ?? null) : null; +} + +function parseAbsolute( + source: string, + { now, zone }: ParseOptions, +): { date?: string; time?: string } | null { + const match = source.match(absoluteTime); + if (!match) return null; + const day = match[1]?.toLowerCase(); + const time = match[2] ?? match[3]; + if (!day) return time ? { time } : null; + if (day.includes("-")) { + if (!isCalendarDate(day)) return null; + return time ? { date: day, time } : { date: day }; + } + const days = + day === "pojutrze" ? 2 : ["tomorrow", "jutro"].includes(day) ? 1 : 0; + const today = Date.parse(`${localAssistantDate(now, zone)}T00:00:00Z`); + const date = new Date(today + days * 86_400_000).toISOString().slice(0, 10); + return time ? { date, time } : { date }; +} + +function parseWhen( + source: string, + options: ParseOptions, +): { dueAt: number } | { date?: string } | null { + if (!source) return {}; + const relative = source.match(relativeTime); + if (relative) { + const count = Number(relative[1]); + const unit = relative[2]?.toLowerCase() ?? ""; + const minutes = count * (/^(?:h|godz)/u.test(unit) ? 60 : 1); + if (minutes < 1 || minutes > 7 * 24 * 60) return null; + return { dueAt: options.now + minutes * 60_000 }; + } + const value = parseAbsolute(source, options); + if (!value) return null; + const { date, time } = value; + if (!date) return {}; + if (date < localAssistantDate(options.now, options.zone)) return null; + if (time) { + const dueAt = resolveAssistantTime(date, time, options.zone); + if (dueAt !== null && dueAt > options.now) return { dueAt }; + } + return { date }; +} + +function addReminder( + text: string, + when: string, + options: ParseOptions, +): AssistantIntent { + if (!text) return invalid; + const schedule = parseWhen(when, options); + if (!schedule) return invalid; + return "dueAt" in schedule + ? { kind: "reminder-set", text, dueAt: schedule.dueAt } + : { kind: "reminder-question", text, ...schedule }; +} + +function moveReminder( + id: string | undefined, + when: string, + options: ParseOptions, +): AssistantIntent { + const schedule = parseWhen(when, options); + if (!schedule) return invalid; + if ("dueAt" in schedule) + return { + kind: "reminder-move", + dueAt: schedule.dueAt, + ...(id ? { id } : {}), + }; + return { kind: "reminder-question", ...(id ? { id } : {}), ...schedule }; +} + +function idFor(value: string, prefix: "T" | "R" | "Q"): string | undefined { + const token = value.trim().toUpperCase().replace(/^#/, ""); + const digits = token.startsWith(prefix) ? token.slice(1) : token; + if (!/^[1-9]\d{0,14}$/.test(digits)) return undefined; + return prefix + digits; +} + +function readId(text: string, prefix: "R" | "Q"): [string, string] | undefined { + const match = text.match(/^(\S+)(?:\s+([\s\S]+))?$/); + const id = match?.[1] ? idFor(match[1], prefix) : undefined; + return id ? [id, match?.[2] ?? ""] : undefined; +} + +function done(source: string): AssistantIntent { + if (!source) return { kind: "task-done" }; + const id = idFor(source, "T"); + return id ? { kind: "task-done", id } : invalid; +} + +function cancel( + kind: "reminder-cancel" | "question-cancel", + source: string, +): AssistantIntent { + const id = idFor(source, kind === "reminder-cancel" ? "R" : "Q"); + return id ? { kind, id } : invalid; +} + +function answer( + source: string, + options: ParseOptions, + questionId?: string, +): AssistantIntent | null { + const value = parseAbsolute(source, options); + if (!value?.time || !clockTime.test(value.time)) return null; + return { + kind: "reminder-answer", + time: value.time, + ...(value.date ? { date: value.date } : {}), + ...(questionId ? { questionId } : {}), + }; +} + +function contentIntent( + kind: "note-add" | "task-add", + text: string, +): AssistantIntent { + return text ? { kind, text } : invalid; +} + +function listNotes(query: string): AssistantIntent { + return query ? { kind: "notes", query } : { kind: "notes" }; +} + +function parseCommand(command: string, options: ParseOptions): AssistantIntent { + const match = command.match(/^(\S+)(?:\s+([\s\S]+))?$/); + const operation = match?.[1]?.toLowerCase() ?? "help"; + const args = match?.[2]?.trim() ?? ""; + switch (operation) { + case "help": + return args ? invalid : help; + case "note": + return contentIntent("note-add", args); + case "notes": + return listNotes(args); + case "task": + return contentIntent("task-add", args); + case "tasks": + return args ? invalid : { kind: "tasks" }; + case "done": + return done(args); + case "remind": { + const separator = args.indexOf("|"); + return separator < 0 + ? invalid + : addReminder( + args.slice(separator + 1).trim(), + args.slice(0, separator).trim(), + options, + ); + } + case "move": { + const parsed = readId(args, "R"); + return parsed ? moveReminder(...parsed, options) : invalid; + } + case "cancel": + return cancel("reminder-cancel", args); + case "reminders": + return args ? invalid : { kind: "reminders" }; + case "answer": { + const parsed = readId(args, "Q"); + return parsed + ? (answer(parsed[1], options, parsed[0]) ?? invalid) + : invalid; + } + case "questions": + return args ? invalid : { kind: "questions" }; + case "question-cancel": + return cancel("question-cancel", args); + default: + return invalid; + } +} + +function stripTopicPrefix(text: string): string { + return text.replace(/^(?:,|:)\s*|^(?:to|about|o|żeby|aby)\s+/iu, "").trim(); +} + +function naturalReminder( + source: string, + options: ParseOptions, +): AssistantIntent { + const prefix = source.match(leadingSchedule)?.[0]; + if (prefix) { + const topic = source + .slice(prefix.length) + .trim() + .replace(/^[,:]\s*/u, ""); + return addReminder(stripTopicPrefix(topic), prefix, options); + } + const suffix = source.match(trailingSchedule); + if (suffix?.[1] && suffix.index !== undefined) { + const topic = source.slice(0, suffix.index).trim(); + if (/(?:^|\s)(?:lub|albo|or)$/iu.test(topic)) return invalid; + return addReminder(stripTopicPrefix(topic), suffix[1], options); + } + return addReminder(stripTopicPrefix(source), "", options); +} + +function naturalMove(source: string, options: ParseOptions): AssistantIntent { + const args = source.replace(/^(?:to|at|na)\s+/iu, ""); + const match = readId(args, "R"); + const when = match ? match[1].replace(/^(?:to|at|na)\s+/iu, "") : args; + const vague = + /^(?:rano|wieczór|wieczorem|po południu|this evening|morning|afternoon)[.!]?$/iu; + return moveReminder(match?.[0], vague.test(when) ? "" : when, options); +} + +export function parseAssistantIntent( + source: string, + options: ParseOptions, +): AssistantIntent { + const message = source.trim(); + if (!message || message.length > 8_000) return invalid; + const command = message.match(/^!assistant(?:\s+([\s\S]*))?$/iu); + if (command) return parseCommand(command[1] ?? "", options); + if (message.startsWith("!")) return invalid; + + if (/^(?:pomoc|help)$/iu.test(message)) return help; + if ( + /^(?:pokaż (?:moje )?(?:otwarte )?(?:zadania|sprawy)|(?:list|show) (?:my )?(?:open )?tasks|zadania|tasks)[.!?]?$/iu.test( + message, + ) + ) + return { kind: "tasks" }; + if ( + /^(?:pokaż (?:moje )?przypomnienia|(?:list|show) (?:my )?reminders|przypomnienia|reminders)[.!?]?$/iu.test( + message, + ) + ) + return { kind: "reminders" }; + + const note = message.match( + /^(?:zapisz(?:\s+notatkę)?|zanotuj|zapamiętaj|save\s+(?:a\s+)?note|take\s+(?:a\s+)?note|remember)(?:\s*[:,]\s*|\s+)([\s\S]+)$/iu, + ); + if (note?.[1]) return contentIntent("note-add", note[1]); + const notes = message.match( + /^(?:pokaż(?:\s+moje)?\s+notatki|(?:znajdź|wyszukaj)\s+notat(?:kę|ki)|(?:find|search|show|list)\s+(?:my\s+)?notes?)(?:\s+(?:(?:o|about|for)\s+)?([\s\S]+))?[.!?]?$/iu, + ); + if (notes) return listNotes(notes[1] ?? ""); + const task = message.match( + /^(?:dodaj\s+zadanie|(?:add|create)\s+(?:a\s+)?task)(?:\s*:\s*|\s+)([\s\S]+)$/iu, + ); + if (task?.[1]) return contentIntent("task-add", task[1]); + const completed = message.match( + /^(?:zrobione|gotowe|ukończ(?:\s+zadanie)?|done|complete(?:\s+task)?|mark(?:\s+task)?)(?:\s+(#?[Tt]?[1-9]\d{0,14}))?(?:\s+done)?[.!]?$/iu, + ); + if (completed) return done(completed[1] ?? ""); + + const reminder = message.match( + /^(?:przypomnij\s+mi|remind\s+me)\s+([\s\S]+)$/iu, + ); + if (reminder?.[1]) return naturalReminder(reminder[1], options); + const cancelled = message.match( + /^(?:anuluj\s+przypomnienie|cancel\s+reminder)\s+(\S+?)[.!]?$/iu, + ); + if (cancelled?.[1]) return cancel("reminder-cancel", cancelled[1]); + const moved = message.match( + /^(?:przełóż(?:\s+(?:przypomnienie|to))?|(?:move|reschedule)(?:\s+(?:reminder|it))?)\s+([\s\S]+)$/iu, + ); + if (moved?.[1]) return naturalMove(moved[1], options); + return answer(message, options) ?? invalid; +} diff --git a/apps/discord-agent/src/assistant-store.ts b/apps/discord-agent/src/assistant-store.ts new file mode 100644 index 0000000..08b5fd8 --- /dev/null +++ b/apps/discord-agent/src/assistant-store.ts @@ -0,0 +1,799 @@ +import { randomUUID } from "node:crypto"; +import { closeSync, lstatSync, openSync } from "node:fs"; +import { DatabaseSync } from "node:sqlite"; +import { + resolveAssistantTime, + type AssistantIntent, +} from "./assistant-intent.js"; + +export const ASSISTANT_SCHEMA_VERSION = 1; +const APPLICATION_ID = 0x504c4f41; // PLOA +const LIST_LIMIT = 12; +const MAX_TEXT_LENGTH = 500; +const MAX_PENDING_ITEMS = 100; +const CLAIM_LEASE_MS = 30_000; +const DISPATCH_LEASE_MS = 120_000; + +interface AssistantScope { + ownerId: string; + threadId: string; + zone: string; +} + +export interface NoteRecord { + id: string; + text: string; + createdAt: number; +} + +export interface TaskRecord extends NoteRecord { + status: "open" | "done"; + dueAt: number | null; +} + +export type ReminderStatus = + | "scheduled" + | "claimed" + | "sending" + | "retry" + | "sent" + | "failed" + | "ambiguous" + | "expired" + | "cancelled"; + +export interface ReminderRecord extends NoteRecord { + status: ReminderStatus; + dueAt: number; + zone: string; + version: number; +} + +export interface QuestionRecord { + id: string; + text: string; + date: string | null; + zone: string; + targetId: string | null; + status: "open" | "resolved" | "cancelled"; + createdAt: number; +} + +type PendingQuestion = QuestionRecord & { targetVersion: number | null }; + +export type AssistantResult = + | { + kind: + | "note_saved" + | "task_added" + | "task_done" + | "reminder_cancelled" + | "question_cancelled"; + id: string; + } + | { kind: "notes"; items: NoteRecord[] } + | { kind: "tasks"; items: TaskRecord[] } + | { kind: "reminder_saved"; item: ReminderRecord } + | { kind: "reminders"; items: ReminderRecord[] } + | { kind: "question_created"; item: QuestionRecord } + | { kind: "questions"; items: QuestionRecord[] } + | { + kind: "problem"; + code: + | "not_found" + | "conflict" + | "invalid_time" + | "no_question" + | "multiple_questions" + | "multiple_tasks" + | "multiple_reminders" + | "invalid" + | "capacity"; + }; + +export interface DeliveryClaim { + id: string; + version: number; + token: string; + text: string; + dueAt: number; + zone: string; + attempt: number; +} + +export type DeliveryOutcome = + | { kind: "sent"; messageId: string } + | { kind: "retry"; retryAt: number } + | { kind: "failed" } + | { kind: "ambiguous" }; + +const schema = ` + CREATE TABLE assistant_scope ( + singleton INTEGER PRIMARY KEY CHECK (singleton=1), + owner_id TEXT NOT NULL, thread_id TEXT NOT NULL + ) STRICT; + CREATE TABLE assistant_operations ( + message_id TEXT PRIMARY KEY, + accepted_at INTEGER NOT NULL, + result_kind TEXT NOT NULL + ) STRICT; + CREATE TABLE assistant_notes ( + id INTEGER PRIMARY KEY, + text TEXT NOT NULL, + searchable_text TEXT NOT NULL, + source_id TEXT NOT NULL, + created_at INTEGER NOT NULL + ) STRICT; + CREATE TABLE assistant_tasks ( + id INTEGER PRIMARY KEY, + text TEXT NOT NULL, + source_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + finished_at INTEGER + ) STRICT; + CREATE TABLE assistant_reminders ( + id INTEGER PRIMARY KEY, + text TEXT NOT NULL, + source_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + due_at INTEGER NOT NULL, + zone TEXT NOT NULL, + version INTEGER NOT NULL DEFAULT 1 CHECK(version > 0) + ) STRICT; + CREATE TABLE assistant_outbox ( + reminder_id INTEGER NOT NULL REFERENCES assistant_reminders(id), + version INTEGER NOT NULL, + state TEXT NOT NULL CHECK(state IN ( + 'scheduled','claimed','sending','retry','sent','failed','ambiguous','expired','cancelled' + )), + next_attempt_at INTEGER NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0, + token TEXT, + lease_until INTEGER, + message_id TEXT, + finished_at INTEGER, + PRIMARY KEY(reminder_id, version) + ) STRICT; + CREATE INDEX assistant_due ON assistant_outbox(state, next_attempt_at); + CREATE INDEX assistant_leases ON assistant_outbox(state, lease_until); + CREATE TABLE assistant_questions ( + id INTEGER PRIMARY KEY, + text TEXT NOT NULL, + source_id TEXT NOT NULL, + local_date TEXT, + zone TEXT NOT NULL, + target_id INTEGER REFERENCES assistant_reminders(id), + target_version INTEGER, + status TEXT NOT NULL DEFAULT 'open' CHECK(status IN ('open','resolved','cancelled')), + created_at INTEGER NOT NULL, + CHECK ((target_id IS NULL) = (target_version IS NULL)) + ) STRICT; + CREATE INDEX assistant_open_questions ON assistant_questions(status, id); +`; + +const reminderFields = `'R'||r.id AS id, r.text, r.created_at AS createdAt, + r.due_at AS dueAt, r.zone, r.version, o.state AS status`; +const currentReminders = `FROM assistant_reminders r JOIN assistant_outbox o + ON o.reminder_id=r.id AND o.version=r.version`; +const questionFields = `'Q'||id AS id, text, local_date AS date, zone, + 'R'||target_id AS targetId, target_version AS targetVersion, status, created_at AS createdAt`; +const moveableStates = "'scheduled','retry','claimed'"; + +function problem( + code: Extract["code"], +): AssistantResult { + return { kind: "problem", code }; +} + +function itemText(raw: string): string | null { + const value = raw.trim(); + return value.length && + value.length <= MAX_TEXT_LENGTH && + !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value) + ? value + : null; +} + +function numberId(raw: string, prefix: "T" | "R" | "Q"): number | null { + const value = raw.toUpperCase(); + const number = value.startsWith(prefix) ? value.slice(1) : value; + return /^[1-9]\d{0,14}$/.test(number) ? Number(number) : null; +} + +function validTimestamp(value: number): boolean { + return ( + Number.isSafeInteger(value) && value >= 0 && value <= 8_640_000_000_000_000 + ); +} + +function folded(text: string): string { + return text.normalize("NFKC").toLowerCase(); +} + +function ensurePrivateFile(path: string): void { + if (path === ":memory:") return; + try { + closeSync(openSync(path, "wx", 0o600)); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + } + const stat = lstatSync(path); + if ( + !stat.isFile() || + stat.nlink !== 1 || + (stat.mode & 0o077) !== 0 || + (process.getuid && stat.uid !== process.getuid()) + ) { + throw new Error( + "Assistant state needs a private regular file owned by the service user", + ); + } +} + +export class AssistantStore { + private readonly db: DatabaseSync; + private readonly zone: string; + + constructor(path: string, scope: AssistantScope) { + if (!scope.ownerId || !scope.threadId) + throw new Error("Assistant scope is required"); + new Intl.DateTimeFormat("en", { timeZone: scope.zone }); + this.zone = scope.zone; + ensurePrivateFile(path); + this.db = new DatabaseSync(path); + try { + this.db.exec("PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000"); + this.transaction(() => { + const version = this.db + .prepare("PRAGMA user_version") + .get()?.user_version; + const application = this.db + .prepare("PRAGMA application_id") + .get()?.application_id; + if (version === 0 && application === 0) { + const tables = this.db + .prepare( + "SELECT name FROM sqlite_schema WHERE substr(name,1,7)<>'sqlite_' LIMIT 1", + ) + .get(); + if (tables) + throw new Error( + "Assistant database already contains unrelated state", + ); + this.db.exec(schema); + this.db.exec( + `PRAGMA user_version=${ASSISTANT_SCHEMA_VERSION}; PRAGMA application_id=${APPLICATION_ID}`, + ); + this.db + .prepare( + "INSERT INTO assistant_scope (singleton,owner_id,thread_id) VALUES (1,?,?)", + ) + .run(scope.ownerId, scope.threadId); + } else if ( + version !== ASSISTANT_SCHEMA_VERSION || + application !== APPLICATION_ID + ) { + throw new Error( + "Unsupported assistant database schema or application", + ); + } + const binding = this.db + .prepare( + "SELECT owner_id, thread_id FROM assistant_scope WHERE singleton=1", + ) + .get(); + if ( + binding?.owner_id !== scope.ownerId || + binding?.thread_id !== scope.threadId + ) { + throw new Error( + "Assistant database is bound to another owner or thread", + ); + } + }); + this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL"); + } catch (error) { + this.db.close(); + throw error; + } + } + + close(): void { + this.db.close(); + } + + private transaction(callback: () => T): T { + this.db.exec("BEGIN IMMEDIATE"); + try { + const value = callback(); + this.db.exec("COMMIT"); + return value; + } catch (error) { + this.db.exec("ROLLBACK"); + throw error; + } + } + + execute( + messageId: string, + intent: AssistantIntent, + now: number, + ): AssistantResult | null { + if (!messageId || !validTimestamp(now)) + throw new Error("Invalid assistant message envelope"); + return this.transaction(() => { + if ( + this.db + .prepare("SELECT 1 FROM assistant_operations WHERE message_id=?") + .get(messageId) + ) + return null; + const result = this.apply(messageId, intent, now); + this.db + .prepare( + "INSERT INTO assistant_operations (message_id,accepted_at,result_kind) VALUES (?,?,?)", + ) + .run(messageId, now, result.kind); + return result; + }); + } + + private apply( + messageId: string, + intent: AssistantIntent, + now: number, + ): AssistantResult { + switch (intent.kind) { + case "help": + case "invalid": + return problem("invalid"); + case "note-add": { + const text = itemText(intent.text); + if (!text) return problem("invalid"); + const row = this.db + .prepare( + "INSERT INTO assistant_notes (text,searchable_text,source_id,created_at) VALUES (?,?,?,?)", + ) + .run(text, folded(text), messageId, now); + return { kind: "note_saved", id: `N${row.lastInsertRowid}` }; + } + case "notes": { + const query = folded(intent.query?.trim() ?? ""); + const items = this.db + .prepare( + `SELECT 'N'||id AS id, text, created_at AS createdAt + FROM assistant_notes WHERE instr(searchable_text,?)>0 ORDER BY id DESC LIMIT ?`, + ) + .all(query, LIST_LIMIT) as unknown as NoteRecord[]; + return { kind: "notes", items }; + } + case "task-add": { + const text = itemText(intent.text); + if (!text) return problem("invalid"); + const row = this.db + .prepare( + "INSERT INTO assistant_tasks (text,source_id,created_at) VALUES (?,?,?)", + ) + .run(text, messageId, now); + return { kind: "task_added", id: `T${row.lastInsertRowid}` }; + } + case "tasks": { + const items = this.db + .prepare( + `SELECT 'T'||id AS id, text, created_at AS createdAt, + 'open' AS status, NULL AS dueAt FROM assistant_tasks + WHERE finished_at IS NULL ORDER BY id DESC LIMIT ?`, + ) + .all(LIST_LIMIT) as unknown as TaskRecord[]; + return { kind: "tasks", items }; + } + case "task-done": + return this.finishTask(intent.id, now); + case "reminder-set": { + const text = itemText(intent.text); + if (!text) return problem("invalid"); + return this.createReminder( + text, + messageId, + intent.dueAt, + this.zone, + now, + ); + } + case "reminder-move": { + const selected = this.selectReminder(intent.id); + return typeof selected === "number" + ? this.moveReminder(selected, intent.dueAt, this.zone, now) + : selected; + } + case "reminder-cancel": + return this.cancelReminder(intent.id, now); + case "reminders": { + const items = this.db + .prepare( + `SELECT ${reminderFields} ${currentReminders} ORDER BY + o.state NOT IN (${moveableStates},'sending'), r.id DESC LIMIT ?`, + ) + .all(LIST_LIMIT) as unknown as ReminderRecord[]; + return { kind: "reminders", items }; + } + case "reminder-question": + return this.askQuestion(messageId, intent, now); + case "reminder-answer": + return this.answerQuestion(messageId, intent, now); + case "questions": + return { kind: "questions", items: this.openQuestions(LIST_LIMIT) }; + case "question-cancel": { + const id = numberId(intent.id, "Q"); + if (!id || !this.closeQuestion(id, "cancelled")) + return problem("no_question"); + return { kind: "question_cancelled", id: `Q${id}` }; + } + } + } + + private finishTask(rawId: string | undefined, now: number): AssistantResult { + let id: number | null; + if (rawId !== undefined) { + id = numberId(rawId, "T"); + } else { + const open = this.db + .prepare( + "SELECT id FROM assistant_tasks WHERE finished_at IS NULL ORDER BY id DESC LIMIT 2", + ) + .all() as unknown as { id: number }[]; + if (open.length > 1) return problem("multiple_tasks"); + id = open[0]?.id ?? null; + } + if (!id) return problem("not_found"); + const change = this.db + .prepare( + "UPDATE assistant_tasks SET finished_at=? WHERE id=? AND finished_at IS NULL", + ) + .run(now, id); + return change.changes + ? { kind: "task_done", id: `T${id}` } + : problem("not_found"); + } + + private reminder(id: number): ReminderRecord | undefined { + return this.db + .prepare(`SELECT ${reminderFields} ${currentReminders} WHERE r.id=?`) + .get(id) as unknown as ReminderRecord | undefined; + } + + private savedReminder(id: number): AssistantResult { + const item = this.reminder(id); + if (!item) throw new Error("Assistant reminder was not saved"); + return { kind: "reminder_saved", item }; + } + + private selectReminder(rawId: string | undefined): number | AssistantResult { + if (rawId !== undefined) + return numberId(rawId, "R") ?? problem("not_found"); + const pending = this.db + .prepare( + `SELECT r.id ${currentReminders} WHERE o.state IN (${moveableStates}) LIMIT 2`, + ) + .all() as unknown as { id: number }[]; + if (pending.length > 1) return problem("multiple_reminders"); + return pending[0]?.id ?? problem("not_found"); + } + + private enqueueDelivery(id: number, version: number, dueAt: number): void { + this.db + .prepare( + "INSERT INTO assistant_outbox (reminder_id,version,state,next_attempt_at) VALUES (?,?,'scheduled',?)", + ) + .run(id, version, dueAt); + } + + private createReminder( + text: string, + messageId: string, + dueAt: number, + zone: string, + now: number, + ): AssistantResult { + if (!validTimestamp(dueAt) || dueAt <= now) return problem("invalid_time"); + if ( + this.db + .prepare( + `SELECT 1 ${currentReminders} + WHERE o.state IN (${moveableStates},'sending') LIMIT 1 OFFSET ?`, + ) + .get(MAX_PENDING_ITEMS - 1) + ) + return problem("capacity"); + const row = this.db + .prepare( + "INSERT INTO assistant_reminders (text,source_id,created_at,due_at,zone) VALUES (?,?,?,?,?)", + ) + .run(text, messageId, now, dueAt, zone); + const id = Number(row.lastInsertRowid); + this.enqueueDelivery(id, 1, dueAt); + return this.savedReminder(id); + } + + private cancelOccurrence(id: number, version: number, now: number): boolean { + return Boolean( + this.db + .prepare( + `UPDATE assistant_outbox + SET state='cancelled', token=NULL, lease_until=NULL, finished_at=? + WHERE reminder_id=? AND version=? AND state IN (${moveableStates})`, + ) + .run(now, id, version).changes, + ); + } + + private cancelTargetQuestions( + id: number, + exceptId: number | null = null, + ): void { + this.db + .prepare( + `UPDATE assistant_questions SET status='cancelled' + WHERE target_id=? AND id IS NOT ? AND status='open'`, + ) + .run(id, exceptId); + } + + private moveReminder( + id: number, + dueAt: number, + zone: string, + now: number, + fromQuestion?: number, + ): AssistantResult { + if (!validTimestamp(dueAt) || dueAt <= now) return problem("invalid_time"); + const item = this.reminder(id); + if (!item) return problem("not_found"); + if (!this.cancelOccurrence(id, item.version, now)) + return problem("conflict"); + const version = item.version + 1; + this.db + .prepare( + "UPDATE assistant_reminders SET version=?, due_at=?, zone=? WHERE id=?", + ) + .run(version, dueAt, zone, id); + this.enqueueDelivery(id, version, dueAt); + this.cancelTargetQuestions(id, fromQuestion); + return this.savedReminder(id); + } + + private cancelReminder(rawId: string, now: number): AssistantResult { + const id = numberId(rawId, "R"); + if (id === null) return problem("not_found"); + const item = this.reminder(id); + if (!item) return problem("not_found"); + if (!this.cancelOccurrence(id, item.version, now)) + return problem("conflict"); + this.cancelTargetQuestions(id); + return { kind: "reminder_cancelled", id: item.id }; + } + + private openQuestions(limit: number): PendingQuestion[] { + return this.db + .prepare( + `SELECT ${questionFields} FROM assistant_questions + WHERE status='open' ORDER BY id DESC LIMIT ?`, + ) + .all(limit) as unknown as PendingQuestion[]; + } + + private question(id: number): PendingQuestion | undefined { + return this.db + .prepare(`SELECT ${questionFields} FROM assistant_questions WHERE id=?`) + .get(id) as unknown as PendingQuestion | undefined; + } + + private closeQuestion(id: number, status: "resolved" | "cancelled"): boolean { + return Boolean( + this.db + .prepare( + "UPDATE assistant_questions SET status=? WHERE id=? AND status='open'", + ) + .run(status, id).changes, + ); + } + + private askQuestion( + messageId: string, + intent: Extract, + now: number, + ): AssistantResult { + if ( + this.db + .prepare( + "SELECT 1 FROM assistant_questions WHERE status='open' LIMIT 1 OFFSET ?", + ) + .get(MAX_PENDING_ITEMS - 1) + ) + return problem("capacity"); + let text: string | null; + let targetId: number | null = null; + let targetVersion: number | null = null; + if (intent.text !== undefined) { + text = itemText(intent.text); + if (!text || intent.id !== undefined) return problem("invalid"); + } else { + const selected = this.selectReminder(intent.id); + if (typeof selected !== "number") return selected; + const item = this.reminder(selected); + if (!item) return problem("not_found"); + if (!["scheduled", "retry", "claimed"].includes(item.status)) + return problem("conflict"); + text = item.text; + targetId = selected; + targetVersion = item.version; + } + const question = this.db + .prepare( + `INSERT INTO assistant_questions + (text,source_id,local_date,zone,target_id,target_version,created_at) + VALUES (?,?,?,?,?,?,?)`, + ) + .run( + text, + messageId, + intent.date ?? null, + this.zone, + targetId, + targetVersion, + now, + ); + const item = this.question(Number(question.lastInsertRowid)); + if (!item) throw new Error("Assistant question was not saved"); + return { kind: "question_created", item }; + } + + private answerQuestion( + messageId: string, + intent: Extract, + now: number, + ): AssistantResult { + let item: PendingQuestion | undefined; + if (intent.questionId !== undefined) { + const id = numberId(intent.questionId, "Q"); + if (id !== null) item = this.question(id); + } else { + const open = this.openQuestions(2); + if (open.length > 1) return problem("multiple_questions"); + item = open[0]; + } + if (!item || item.status !== "open") return problem("no_question"); + const date = intent.date ?? item.date; + if (!date) return problem("invalid_time"); + const dueAt = resolveAssistantTime(date, intent.time, item.zone); + if (dueAt === null || !validTimestamp(dueAt) || dueAt <= now) + return problem("invalid_time"); + const questionId = numberId(item.id, "Q")!; + let result: AssistantResult; + if (item.targetId === null) { + result = this.createReminder(item.text, messageId, dueAt, item.zone, now); + } else { + const target = numberId(item.targetId, "R")!; + if (this.reminder(target)?.version !== item.targetVersion) { + this.closeQuestion(questionId, "cancelled"); + return problem("conflict"); + } + result = this.moveReminder(target, dueAt, item.zone, now, questionId); + if (result.kind === "problem" && result.code === "conflict") + this.closeQuestion(questionId, "cancelled"); + } + if (result.kind === "reminder_saved") + this.closeQuestion(questionId, "resolved"); + return result; + } + + private recoverExpiredLeases(now: number): void { + this.db + .prepare( + `UPDATE assistant_outbox SET state='scheduled', token=NULL, lease_until=NULL + WHERE state='claimed' AND lease_until<=?`, + ) + .run(now); + this.db + .prepare( + `UPDATE assistant_outbox SET state='ambiguous', token=NULL, lease_until=NULL, finished_at=? + WHERE state='sending' AND lease_until<=?`, + ) + .run(now, now); + } + + recoverDeliveries(now: number): void { + if (!validTimestamp(now)) + throw new Error("Invalid assistant delivery clock"); + this.transaction(() => this.recoverExpiredLeases(now)); + } + + claimDue(now: number, maxLatenessMs: number): DeliveryClaim | null { + if ( + !validTimestamp(now) || + !Number.isSafeInteger(maxLatenessMs) || + maxLatenessMs < 0 + ) { + throw new Error("Invalid assistant delivery clock or lateness window"); + } + return this.transaction(() => { + this.recoverExpiredLeases(now); + this.db + .prepare( + `UPDATE assistant_outbox SET state='expired', finished_at=? + WHERE state IN ('scheduled','retry') AND EXISTS ( + SELECT 1 FROM assistant_reminders r + WHERE r.id=assistant_outbox.reminder_id AND r.version=assistant_outbox.version AND r.due_at | undefined; + if (!row) return null; + const token = randomUUID(); + this.db + .prepare( + `UPDATE assistant_outbox SET state='claimed', token=?, lease_until=? + WHERE reminder_id=? AND version=?`, + ) + .run(token, now + CLAIM_LEASE_MS, numberId(row.id, "R"), row.version); + return { ...row, token }; + }); + } + + beginDelivery(claim: DeliveryClaim, now: number): boolean { + if (!validTimestamp(now)) + throw new Error("Invalid assistant delivery clock"); + const id = numberId(claim.id, "R"); + return Boolean( + this.db + .prepare( + `UPDATE assistant_outbox SET state='sending', + attempts=attempts+1, lease_until=? + WHERE reminder_id=? AND version=? AND token=? AND state='claimed' AND lease_until>? + AND EXISTS (SELECT 1 FROM assistant_reminders r WHERE r.id=? AND r.version=?)`, + ) + .run( + now + DISPATCH_LEASE_MS, + id, + claim.version, + claim.token, + now, + id, + claim.version, + ).changes, + ); + } + + finishDelivery( + claim: DeliveryClaim, + outcome: DeliveryOutcome, + now: number, + ): void { + const retryAt = outcome.kind === "retry" ? outcome.retryAt : now; + if (!validTimestamp(now) || !validTimestamp(retryAt) || retryAt < now) { + throw new Error("Invalid assistant delivery completion time"); + } + this.db + .prepare( + `UPDATE assistant_outbox SET state=?, next_attempt_at=?, message_id=?, + token=NULL, lease_until=NULL, finished_at=? + WHERE reminder_id=? AND version=? AND token=? AND state='sending'`, + ) + .run( + outcome.kind, + retryAt, + outcome.kind === "sent" ? outcome.messageId : null, + outcome.kind === "retry" ? null : now, + numberId(claim.id, "R"), + claim.version, + claim.token, + ); + } +} diff --git a/apps/discord-agent/src/assistant.ts b/apps/discord-agent/src/assistant.ts new file mode 100644 index 0000000..5dc621e --- /dev/null +++ b/apps/discord-agent/src/assistant.ts @@ -0,0 +1,205 @@ +import { + authorized, + redact, + SNOWFLAKE, + type Config, + type Incoming, +} from "./config.js"; +import { + formatAssistantTime, + parseAssistantIntent, +} from "./assistant-intent.js"; +import type { AssistantResult, AssistantStore } from "./assistant-store.js"; + +export type AssistantLocale = "en" | "pl"; + +export interface AssistantSettings { + threadId: string; + locale: AssistantLocale; + zone: string; + maxLatenessMs: number; +} + +export function loadAssistantSettings( + env = process.env, +): AssistantSettings | undefined { + const threadId = env.PLOMPY_ASSISTANT_THREAD_ID; + if (!threadId) return undefined; + if (!SNOWFLAKE.test(threadId)) throw new Error("Invalid assistant thread ID"); + const locale = env.PLOMPY_ASSISTANT_LOCALE ?? "en"; + if (locale !== "en" && locale !== "pl") + throw new Error("Invalid assistant locale"); + const zone = env.PLOMPY_ASSISTANT_TIME_ZONE ?? "UTC"; + if (!/^[A-Za-z][A-Za-z0-9_+-]*(\/[A-Za-z0-9_+-]+)*$/.test(zone)) + throw new Error("Expected an IANA assistant time zone"); + new Intl.DateTimeFormat("en", { timeZone: zone }); + const minutes = env.PLOMPY_ASSISTANT_MAX_LATE_MINUTES ?? ""; + if (!/^[1-9]\d{0,3}$/.test(minutes) || Number(minutes) > 1440) + throw new Error( + "Choose an assistant late-delivery window from 1 to 1440 minutes", + ); + return { threadId, locale, zone, maxLatenessMs: Number(minutes) * 60_000 }; +} + +type AssistantTransport = { + send(threadId: string, text: string): Promise; +}; + +const help = [ + "`!assistant note TEXT` · `!assistant notes [QUERY]`", + "`!assistant task TEXT` · `!assistant tasks` · `!assistant done [T1]`", + "`!assistant remind tomorrow 14:30 | TEXT` · `!assistant reminders`", + "`!assistant move R1 tomorrow 15:00` · `!assistant cancel R1`", + "`!assistant questions` · `!assistant answer Q1 14:30` · `!assistant question-cancel Q1`", +].join("\n"); + +const deliveryStates = { + scheduled: ["scheduled", "zaplanowane"], + claimed: ["preparing", "przygotowywane"], + sending: ["sending", "w trakcie wysyłki"], + retry: ["waiting to retry", "oczekuje na ponowienie"], + sent: ["accepted by Discord", "przyjęte przez Discorda"], + failed: ["delivery failed", "wysyłka nieudana"], + ambiguous: ["delivery uncertain", "wynik wysyłki niepewny"], + expired: ["missed after downtime", "po terminie"], + cancelled: ["cancelled", "anulowane"], +} as const; + +function formatResult( + result: AssistantResult, + settings: AssistantSettings, +): string { + const pl = settings.locale === "pl"; + const format = (time: number, zone: string) => + formatAssistantTime(time, zone, settings.locale); + const rows = (lines: string[]) => + lines.length ? lines.join("\n") : pl ? "Brak wpisów." : "No entries."; + switch (result.kind) { + case "note_saved": + return pl ? `Zapisana notatka ${result.id}.` : `Saved note ${result.id}.`; + case "notes": + return rows(result.items.map(({ id, text }) => `**${id}** · ${text}`)); + case "task_added": + return pl ? `Zapisane zadanie ${result.id}.` : `Added task ${result.id}.`; + case "tasks": + return rows(result.items.map(({ id, text }) => `**${id}** · ${text}`)); + case "task_done": + return pl + ? `Zadanie ${result.id} wykonane.` + : `Completed task ${result.id}.`; + case "reminder_saved": + return pl + ? `Przypomnienie ${result.item.id} zapisane na ${format(result.item.dueAt, result.item.zone)}.` + : `Reminder ${result.item.id} scheduled for ${format(result.item.dueAt, result.item.zone)}.`; + case "reminders": + return rows( + result.items.map( + (item) => + `**${item.id}** · ${format(item.dueAt, item.zone)} · ${deliveryStates[item.status][pl ? 1 : 0]}\n${item.text}`, + ), + ); + case "reminder_cancelled": + return pl + ? `Przypomnienie ${result.id} anulowane.` + : `Cancelled reminder ${result.id}.`; + case "question_created": { + const { date, id } = result.item; + const answer = date ? "14:30" : "2030-01-25 14:30"; + return pl + ? `**${id}** · ${date ? `O której godzinie (${date})?` : "Którego dnia i o której godzinie?"}\nPrzykład odpowiedzi: \`!assistant answer ${id} ${answer}\`.` + : `**${id}** · ${date ? `At what time (${date})?` : "On which day and at what time?"}\nExample reply: \`!assistant answer ${id} ${answer}\`.`; + } + case "questions": + return rows( + result.items.map( + ({ id, date, text }) => + `**${id}** · ${date ?? (pl ? "brak daty" : "date needed")} · ${text}`, + ), + ); + case "question_cancelled": + return pl + ? `Pytanie ${result.id} anulowane.` + : `Cancelled question ${result.id}.`; + case "problem": { + if (result.code === "no_question") + return pl + ? "Brak otwartego pytania o termin." + : "There is no open question about a reminder."; + if (result.code === "multiple_questions") + return pl + ? "Podaj ID pytania. Wpisz `!assistant questions`, żeby zobaczyć listę." + : "Specify the question ID. Use `!assistant questions` to list them."; + if (result.code === "multiple_tasks") + return pl + ? "Które zadanie jest wykonane? Wpisz `!assistant tasks`, a potem np. `!assistant done T1`." + : "Which task is complete? Use `!assistant tasks`, then e.g. `!assistant done T1`."; + if (result.code === "multiple_reminders") + return pl + ? "Które przypomnienie przełożyć? Wpisz `!assistant reminders`, a potem np. `!assistant move R1 tomorrow 15:00`." + : "Which reminder should move? Use `!assistant reminders`, then e.g. `!assistant move R1 tomorrow 15:00`."; + if (result.code === "invalid_time") + return pl + ? "Podaj przyszłą datę i jednoznaczną godzinę. Przy zmianie czasu użyj przesunięcia, np. `02:30 UTC+01:00`." + : "Give a future date and an unambiguous time. For a clock change, include the offset, e.g. `02:30 UTC+01:00`."; + if (result.code === "conflict") + return pl + ? "Wpis już się zmienił albo trwa jego wysyłka. Sprawdź aktualną listę przed kolejną zmianą." + : "The entry changed or is already being sent. Check the list before trying again."; + if (result.code === "not_found") + return pl + ? "Podaj ID z aktualnej listy." + : "Specify an ID from the current list."; + if (result.code === "capacity") + return pl + ? "Osiągnięto limit otwartych wpisów." + : "The open-entry limit has been reached."; + return (pl ? "Sprawdź polecenie.\n" : "Check the command.\n") + help; + } + } +} + +export class PersonalAssistant { + constructor( + private config: Pick, + private settings: AssistantSettings, + private store: Pick, + private transport: AssistantTransport, + private now = Date.now, + ) {} + + async handle(message: Incoming): Promise { + if (message.channelId !== this.settings.threadId) return false; + if (!authorized(message, this.config)) return true; + const { threadId, locale, zone } = this.settings; + const now = this.now(); + const createdAt = Number(BigInt(message.id) >> 22n) + 1_420_070_400_000; + const intent = message.attachments + ? { kind: "invalid" as const } + : parseAssistantIntent(redact(message.content, this.config.token), { + now: createdAt, + zone, + locale, + }); + if (intent.kind === "help" || intent.kind === "invalid") { + await this.transport.send(threadId, help); + return true; + } + if ( + intent.kind === "reminder-answer" && + message.replyToId && + !intent.questionId + ) { + await this.transport.send( + threadId, + locale === "pl" + ? "W odpowiedzi Discord podaj ID pytania, np. `!assistant answer Q1 14:30`." + : "Include the question ID in a Discord reply, e.g. `!assistant answer Q1 14:30`.", + ); + return true; + } + const result = this.store.execute(message.id, intent, now); + if (result) + await this.transport.send(threadId, formatResult(result, this.settings)); + return true; + } +} diff --git a/apps/discord-agent/src/config.ts b/apps/discord-agent/src/config.ts index 99ea472..904ead7 100644 --- a/apps/discord-agent/src/config.ts +++ b/apps/discord-agent/src/config.ts @@ -314,6 +314,7 @@ export interface Incoming { content: string; attachments: number; images?: IncomingImage[]; + replyToId?: string; } export function authorized( message: Incoming, diff --git a/apps/discord-agent/src/discord.ts b/apps/discord-agent/src/discord.ts index be43b1e..4c90c35 100644 --- a/apps/discord-agent/src/discord.ts +++ b/apps/discord-agent/src/discord.ts @@ -4,11 +4,16 @@ import { ChannelType, PermissionFlagsBits, AttachmentBuilder, + DiscordAPIError, Events, + HTTPError, + RateLimitError, + RequestMethod, type Message, } from "discord.js"; import { redact, type Config, type Incoming } from "./config.js"; import type { Transport } from "./engine.js"; +import type { ReminderSendResult } from "./assistant-delivery.js"; export function splitMessage(text: string, max = 1800): string[] { const chunks: string[] = []; let rest = text; @@ -25,16 +30,28 @@ export function splitMessage(text: string, max = 1800): string[] { return chunks.length ? chunks : ["Completed."]; } export class DiscordTransport implements Transport { - readonly client = new Client({ - intents: [ - GatewayIntentBits.Guilds, - GatewayIntentBits.GuildMessages, - GatewayIntentBits.MessageContent, - ], - allowedMentions: { parse: [], repliedUser: false }, - rest: { retries: 0, timeout: 15000 }, - }); - constructor(private config: Config) {} + readonly client: Client; + constructor( + private config: Config, + assistantThreadId?: string, + ) { + this.client = new Client({ + intents: [ + GatewayIntentBits.Guilds, + GatewayIntentBits.GuildMessages, + GatewayIntentBits.MessageContent, + ], + allowedMentions: { parse: [], repliedUser: false }, + rest: { + retries: 0, + timeout: 15000, + rejectOnRateLimit: ({ method, majorParameter, route }) => + method.toUpperCase() === RequestMethod.Post && + route === "/channels/:id/messages" && + majorParameter === assistantThreadId, + }, + }); + } async validate(): Promise { if (this.client.user?.id !== this.config.botId) throw new Error("Wrong bot identity"); @@ -107,6 +124,44 @@ export class DiscordTransport implements Transport { const channel = await this.thread(threadId); await channel.sendTyping(); } + async sendReminder( + threadId: string, + text: string, + ): Promise { + let thread: Awaited>; + try { + await this.validate(); + thread = await this.thread(threadId); + } catch (error) { + if (error instanceof RateLimitError) + return { kind: "retry", retryAfterMs: error.retryAfter }; + if ( + ((error instanceof DiscordAPIError || error instanceof HTTPError) && + error.status >= 500) || + error instanceof TypeError || + (error instanceof Error && + ["AbortError", "TimeoutError"].includes(error.name)) + ) + return { kind: "retry" }; + return { kind: "failed" }; + } + try { + const message = await thread.send({ + content: redact(text, this.config.token), + allowedMentions: { parse: [], repliedUser: false }, + }); + return { kind: "sent", messageId: message.id }; + } catch (error) { + if (error instanceof RateLimitError) + return { kind: "retry", retryAfterMs: error.retryAfter }; + if (error instanceof DiscordAPIError || error instanceof HTTPError) { + if (error.status === 429) return { kind: "retry" }; + if (error.status >= 400 && error.status < 500 && error.status !== 408) + return { kind: "failed" }; + } + return { kind: "ambiguous" }; + } + } onMessage(handler: (message: Incoming) => Promise): void { this.client.on(Events.MessageCreate, (message: Message) => { const channel = message.channel; @@ -121,6 +176,9 @@ export class DiscordTransport implements Transport { thread: channel.isThread(), content: message.content, attachments: message.attachments.size, + ...(message.reference?.messageId + ? { replyToId: message.reference.messageId } + : {}), images: [...message.attachments.values()].map((attachment) => ({ id: attachment.id, url: attachment.url, diff --git a/apps/discord-agent/src/index.ts b/apps/discord-agent/src/index.ts index 6e062f1..bafbe09 100644 --- a/apps/discord-agent/src/index.ts +++ b/apps/discord-agent/src/index.ts @@ -6,9 +6,13 @@ import { Store } from "./store.js"; import { Engine } from "./engine.js"; import { DiscordTransport } from "./discord.js"; import { assertSupportedRuntime } from "./node-runtime.js"; +import { loadAssistantSettings, PersonalAssistant } from "./assistant.js"; +import { AssistantStore } from "./assistant-store.js"; +import { ReminderScheduler } from "./assistant-delivery.js"; async function main(): Promise { assertSupportedRuntime(); const config = loadConfig(); + const assistantSettings = loadAssistantSettings(); // The token remains only in the transport's memory and never enters child envs. delete process.env.DISCORD_BOT_TOKEN; delete process.env.PLOMPY_GIT_SSH_COMMAND; @@ -25,22 +29,65 @@ async function main(): Promise { await realpath(config.workspace); await cleanupStaleImages(config.stateDir); const store = new Store(join(config.stateDir, "agent.sqlite")); - const recovered = store.recoverStartup(); - const transport = new DiscordTransport(config), + const transport = new DiscordTransport(config, assistantSettings?.threadId), engine = new Engine(config, store, transport); let ready = false; - transport.onMessage((message) => - ready ? engine.accept(message) : Promise.resolve(false), - ); + let assistantStore: AssistantStore | undefined; + let assistant: PersonalAssistant | undefined; + let scheduler: ReminderScheduler | undefined; + const reportAssistantFailure = () => + console.error( + JSON.stringify({ event: "assistant_delivery", status: "error" }), + ); + transport.onMessage(async (message) => { + if (!ready) return false; + if (assistant && (await assistant.handle(message))) return true; + return engine.accept(message); + }); + let recovered: ReturnType; try { + recovered = store.recoverStartup(); await transport.connect(); + if (assistantSettings) { + await transport.thread(assistantSettings.threadId); + assistantStore = new AssistantStore( + join(config.stateDir, "assistant.sqlite"), + { + ownerId: config.ownerId, + threadId: assistantSettings.threadId, + zone: assistantSettings.zone, + }, + ); + assistant = new PersonalAssistant( + config, + assistantSettings, + assistantStore, + transport, + ); + scheduler = new ReminderScheduler( + assistantStore, + transport.sendReminder.bind(transport), + { + ...assistantSettings, + onError: reportAssistantFailure, + }, + ); + scheduler.start(); + } } catch (error) { transport.close(); + assistantStore?.close(); store.close(); throw error; } ready = true; - console.log(JSON.stringify({ event: "ready", interruptedJobs: recovered })); + console.log( + JSON.stringify({ + event: "ready", + interruptedJobs: recovered, + assistant: !!assistant, + }), + ); void engine.kick(); const tick = setInterval(() => { void engine.kick(); @@ -52,9 +99,11 @@ async function main(): Promise { ready = false; clearInterval(tick); engine.stop(); + await scheduler?.stop().catch(reportAssistantFailure); while (engine.isBusy()) await new Promise((resolve) => setTimeout(resolve, 100)); transport.close(); + assistantStore?.close(); store.close(); }; process.on("SIGTERM", () => { diff --git a/apps/discord-agent/test/assistant-delivery.test.mjs b/apps/discord-agent/test/assistant-delivery.test.mjs new file mode 100644 index 0000000..30a83dd --- /dev/null +++ b/apps/discord-agent/test/assistant-delivery.test.mjs @@ -0,0 +1,290 @@ +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; +import { ReminderScheduler } from "../dist/assistant-delivery.js"; +import { AssistantStore } from "../dist/assistant-store.js"; + +const threadId = "100000000000000001"; +const receiptId = "100000000000000002"; +const dueAt = Date.parse("2030-01-02T09:30:00Z"); +const maxLatenessMs = 30 * 60_000; + +function claim(overrides = {}) { + return { + id: "r-123", + version: 1, + token: "test-lease", + text: "Water the fern", + dueAt, + zone: "Europe/Warsaw", + attempt: 1, + ...overrides, + }; +} + +function reminderScheduler(store, send, overrides = {}) { + return new ReminderScheduler(store, send, { + threadId, + locale: "en", + maxLatenessMs, + now: () => dueAt, + ...overrides, + }); +} + +test("reminders start independently of a busy runner and ticks share one in-flight send", async () => { + const pendingRunner = Promise.withResolvers(); + const dispatchStarted = Promise.withResolvers(); + const pendingSend = Promise.withResolvers(); + let runnerFinished = false; + const runner = pendingRunner.promise.then(() => { + runnerFinished = true; + }); + const original = claim(); + const now = dueAt + 120_000; + const events = []; + const store = { + recoverDeliveries(at) { + events.push(["recover", at]); + }, + claimDue(at, lateness) { + events.push(["claim", at, lateness]); + return original; + }, + beginDelivery(value, at) { + events.push(["begin", value, at]); + return true; + }, + finishDelivery(value, outcome, at) { + events.push(["finish", value, outcome, at]); + }, + }; + const scheduler = reminderScheduler( + store, + (target, content) => { + dispatchStarted.resolve({ target, content }); + return pendingSend.promise; + }, + { locale: "pl", now: () => now }, + ); + try { + scheduler.start(); + const { target, content } = await dispatchStarted.promise; + assert.equal(target, threadId); + assert.match(content, /Opóźnione przypomnienie r-123/); + assert.match(content, /10:30 \(Europe\/Warsaw\)/); + assert.match(content, /Water the fern/); + assert.equal(runnerFinished, false); + const first = scheduler.tick(); + assert.equal(first, scheduler.tick()); + const shuttingDown = scheduler.stop(); + pendingSend.resolve({ kind: "sent", messageId: receiptId }); + await shuttingDown; + await first; + await scheduler.tick(); + assert.deepEqual(events, [ + ["recover", now], + ["claim", now, maxLatenessMs], + ["begin", original, now], + ["finish", original, { kind: "sent", messageId: receiptId }, now], + ]); + } finally { + pendingSend.resolve({ kind: "sent", messageId: receiptId }); + await scheduler.stop(); + pendingRunner.resolve(); + await runner; + } +}); + +test("a cancelled or rescheduled claim cannot reach the transport", async () => { + const original = claim(); + let reservations = 0; + const scheduler = reminderScheduler( + { + claimDue: () => (reservations++ === 0 ? original : null), + beginDelivery(value) { + assert.equal(value, original); + return false; + }, + finishDelivery: () => + assert.fail("A superseded claim must not be finished"), + }, + () => assert.fail("A superseded claim must not be sent"), + ); + await scheduler.tick(); + assert.equal(reservations, 2); +}); + +test("explicitly rejected sends honor Retry-After and stop after three attempts", async () => { + let now = dueAt; + let availableAt = dueAt; + let attempts = 0; + const outcomes = []; + const scheduler = reminderScheduler( + { + claimDue: (at) => + at >= availableAt && attempts < 3 + ? claim({ attempt: attempts + 1 }) + : null, + beginDelivery() { + attempts++; + return true; + }, + finishDelivery(_, outcome) { + outcomes.push(outcome); + if (outcome.kind === "retry") availableAt = outcome.retryAt; + }, + }, + async () => + attempts === 1 + ? { kind: "retry", retryAfterMs: 50_000 } + : { kind: "retry" }, + { now: () => now }, + ); + await scheduler.tick(); + now += 49_999; + await scheduler.tick(); + assert.equal(attempts, 1); + now++; + await scheduler.tick(); + assert.equal(attempts, 2); + now += 30_000; + await scheduler.tick(); + assert.equal(attempts, 3); + assert.deepEqual(outcomes, [ + { kind: "retry", retryAt: dueAt + 50_000 }, + { kind: "retry", retryAt: dueAt + 80_000 }, + { kind: "failed" }, + ]); +}); + +test("transport errors of unknown outcome are recorded as ambiguous without retry", async () => { + let pending = claim(); + const outcomes = []; + const scheduler = reminderScheduler( + { + claimDue() { + const current = pending; + pending = null; + return current; + }, + beginDelivery: () => true, + finishDelivery: (_, outcome) => outcomes.push(outcome), + }, + async () => { + throw new Error("Connection closed before acknowledgement"); + }, + ); + await scheduler.tick(); + await scheduler.tick(); + assert.deepEqual(outcomes, [{ kind: "ambiguous" }]); +}); + +test("definitive rate limits beyond the configured lateness window end the attempt", async () => { + let pending = claim(); + const outcomes = []; + const scheduler = reminderScheduler( + { + claimDue() { + const current = pending; + pending = null; + return current; + }, + beginDelivery: () => true, + finishDelivery: (_, outcome) => outcomes.push(outcome), + }, + async () => ({ kind: "retry", retryAfterMs: 7200_000 }), + ); + await scheduler.tick(); + assert.deepEqual(outcomes, [{ kind: "failed" }]); +}); + +test("a poll sends at most four reminders so a backlog cannot flood a thread at once", async () => { + let sends = 0; + const scheduler = reminderScheduler( + { + claimDue: () => claim(), + beginDelivery: () => true, + finishDelivery() {}, + }, + async () => { + sends++; + return { kind: "sent", messageId: receiptId }; + }, + ); + await scheduler.tick(); + assert.equal(sends, 4); +}); + +test("a new scheduler delivers recent persisted reminders and expires older ones", async (t) => { + const dir = await mkdtemp(join(tmpdir(), "plompy-reminder-test-")); + t.after(() => rm(dir, { recursive: true })); + const path = join(dir, "assistant.sqlite"); + const scope = { + ownerId: "100000000000000003", + threadId, + zone: "Europe/Warsaw", + }; + const now = dueAt + 60_000; + let store = new AssistantStore(path, scope); + try { + const staleAt = dueAt - maxLatenessMs; + store.execute( + "100000000000000004", + { + kind: "reminder-set", + dueAt: staleAt, + text: "Old reminder", + }, + staleAt - 60_000, + ); + store.execute( + "100000000000000005", + { + kind: "reminder-set", + dueAt, + text: "Recent reminder", + }, + dueAt - 60_000, + ); + } finally { + store.close(); + } + + const messages = []; + const send = async (target, content) => { + messages.push({ target, content }); + return { kind: "sent", messageId: receiptId }; + }; + store = new AssistantStore(path, scope); + try { + await reminderScheduler(store, send, { now: () => now }).tick(); + } finally { + store.close(); + } + + store = new AssistantStore(path, scope); + try { + await reminderScheduler(store, send, { now: () => now }).tick(); + const records = store.execute( + "100000000000000006", + { kind: "reminders" }, + now, + ); + assert.equal(records.kind, "reminders"); + assert.deepEqual( + Object.fromEntries( + records.items.map(({ text, status }) => [text, status]), + ), + { "Old reminder": "expired", "Recent reminder": "sent" }, + ); + } finally { + store.close(); + } + assert.equal(messages.length, 1); + assert.equal(messages[0].target, threadId); + assert.match(messages[0].content, /Delayed reminder R2/); + assert.match(messages[0].content, /Recent reminder/); +}); diff --git a/apps/discord-agent/test/assistant-intent.test.mjs b/apps/discord-agent/test/assistant-intent.test.mjs new file mode 100644 index 0000000..83ef824 --- /dev/null +++ b/apps/discord-agent/test/assistant-intent.test.mjs @@ -0,0 +1,171 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + formatAssistantTime, + localAssistantDate, + parseAssistantIntent, + resolveAssistantTime, +} from "../dist/assistant-intent.js"; + +const zone = "Europe/Warsaw"; +const now = Date.parse("2026-11-18T23:15:00Z"); +const parse = (text, locale = "pl") => + parseAssistantIntent(text, { now, zone, locale }); + +test("Polish and English requests preserve note text and allow tasks without a due date", () => { + const content = "Pomysł do rolki o retry; webhooki\ni przykład."; + assert.deepEqual(parse(`Zapisz ${content}`), { + kind: "note-add", + text: content, + }); + assert.deepEqual(parse("Save a note: Keep the API header as-is", "en"), { + kind: "note-add", + text: "Keep the API header as-is", + }); + assert.deepEqual(parse("Znajdź notatkę o retry"), { + kind: "notes", + query: "retry", + }); + assert.deepEqual(parse("Pokaż notatki"), { kind: "notes" }); + assert.deepEqual(parse("Dodaj zadanie: kupić filtr"), { + kind: "task-add", + text: "kupić filtr", + }); + assert.deepEqual(parse("Pokaż otwarte sprawy"), { kind: "tasks" }); + assert.deepEqual(parse("Zrobione"), { kind: "task-done" }); + assert.deepEqual(parse("!assistant done #2"), { + kind: "task-done", + id: "T2", + }); +}); + +test("tomorrow means the next local day at message receipt, before any later handling", () => { + assert.equal(localAssistantDate(now, zone), "2026-11-19"); + assert.deepEqual(parse("Przypomnij mi jutro o filtrze"), { + kind: "reminder-question", + text: "filtrze", + date: "2026-11-20", + }); + const dueAt = Date.parse("2026-11-20T17:30:00Z"); + assert.deepEqual(parse("Przypomnij mi jutro o 18:30, żeby kupić filtr"), { + kind: "reminder-set", + text: "kupić filtr", + dueAt, + }); + assert.deepEqual(parse("Remind me to buy a filter tomorrow at 18:30", "en"), { + kind: "reminder-set", + text: "buy a filter", + dueAt, + }); + assert.deepEqual( + parse("!assistant remind tomorrow 18:30 | Buy a filter", "en"), + { + kind: "reminder-set", + text: "Buy a filter", + dueAt, + }, + ); + assert.match( + formatAssistantTime(dueAt, zone, "pl"), + /20 listopada 2026.*18:30.*Europe\/Warsaw/, + ); +}); + +test("relative times, moving, canceling and answering use bounded, typed arguments", () => { + assert.deepEqual(parse("Przypomnij mi za 5 minut o filtrze"), { + kind: "reminder-set", + text: "filtrze", + dueAt: now + 5 * 60_000, + }); + assert.deepEqual(parse("Remind me to stretch in 1 hour", "en"), { + kind: "reminder-set", + text: "stretch", + dueAt: now + 60 * 60_000, + }); + assert.deepEqual(parse("Przełóż to na jutro o 16:00"), { + kind: "reminder-move", + dueAt: Date.parse("2026-11-20T15:00:00Z"), + }); + assert.deepEqual(parse("!assistant move r2 jutro"), { + kind: "reminder-question", + id: "R2", + date: "2026-11-20", + }); + assert.deepEqual(parse("Anuluj przypomnienie #3."), { + kind: "reminder-cancel", + id: "R3", + }); + assert.deepEqual(parse("!assistant reminders"), { kind: "reminders" }); + assert.deepEqual(parse("O 18:30"), { + kind: "reminder-answer", + time: "18:30", + }); + assert.deepEqual(parse("!assistant answer #4 jutro o 18:30"), { + kind: "reminder-answer", + questionId: "Q4", + date: "2026-11-20", + time: "18:30", + }); + assert.deepEqual(parse("!assistant questions"), { kind: "questions" }); + assert.deepEqual(parse("!assistant question-cancel q4"), { + kind: "question-cancel", + id: "Q4", + }); +}); + +test("invalid calendar dates and DST gaps are rejected and folds require the actual offset", () => { + assert.equal(resolveAssistantTime("2026-02-30", "18:30", zone), null); + assert.equal(resolveAssistantTime("2026-03-29", "25:00", zone), null); + assert.equal(resolveAssistantTime("2026-03-29", "02:30", zone), null); + assert.equal( + resolveAssistantTime("2026-03-29", "02:30 UTC+02:00", zone), + null, + ); + assert.equal(resolveAssistantTime("2026-10-25", "02:30", zone), null); + assert.equal( + resolveAssistantTime("2026-10-25", "02:30 UTC+02:00", zone), + Date.parse("2026-10-25T00:30:00Z"), + ); + assert.equal( + resolveAssistantTime("2026-10-25", "02:30 UTC+01:00", zone), + Date.parse("2026-10-25T01:30:00Z"), + ); + assert.equal( + resolveAssistantTime("2026-10-25", "02:30 UTC+03:00", zone), + null, + ); + const inOctober = (text) => + parseAssistantIntent(text, { + now: Date.parse("2026-10-24T10:00:00Z"), + zone, + locale: "pl", + }); + assert.deepEqual(inOctober("Przypomnij mi jutro o 02:30 o starcie"), { + kind: "reminder-question", + text: "starcie", + date: "2026-10-25", + }); + assert.deepEqual(inOctober("!assistant answer Q10 02:30 UTC+01:00"), { + kind: "reminder-answer", + questionId: "Q10", + time: "02:30 UTC+01:00", + }); +}); + +test("unrecognized and malformed requests cannot guess an operation or a date", () => { + for (const message of [ + "Tak", + "!assistant fake anything", + "!assistant tasks ignore that other thing", + "!assistant note", + "!assistant cancel T3", + "!assistant remind 2026-02-30 18:30 | Filter", + "!assistant remind 2026-11-17 18:30 | Filter", + "!assistant remind in 0 minutes | Filter", + "Przypomnij mi o filtrze jutro albo pojutrze", + "25:30", + "!work 30m", + ]) + assert.equal(parse(message).kind, "invalid", message); + assert.deepEqual(parse("!assistant help"), { kind: "help" }); +}); diff --git a/apps/discord-agent/test/assistant-store.test.mjs b/apps/discord-agent/test/assistant-store.test.mjs new file mode 100644 index 0000000..266c4f1 --- /dev/null +++ b/apps/discord-agent/test/assistant-store.test.mjs @@ -0,0 +1,360 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { chmodSync, mkdtempSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import { + AssistantStore, + ASSISTANT_SCHEMA_VERSION, +} from "../dist/assistant-store.js"; + +const scope = { + ownerId: "910000000000000001", + threadId: "920000000000000001", + zone: "Europe/Warsaw", +}; +const now = Date.parse("2030-02-20T12:00:00Z"); +const minute = 60_000; +const source = (n) => String(930000000000000000n + BigInt(n)); + +function file(t) { + const dir = mkdtempSync(join(tmpdir(), "plompy-assistant-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + return join(dir, "assistant.sqlite"); +} + +function reminder(store, index, dueAt = now + minute) { + return store.execute( + source(index), + { kind: "reminder-set", text: `Test reminder ${index}`, dueAt }, + now, + ); +} + +function status(store, index) { + const result = store.execute(source(index), { kind: "reminders" }, now); + assert.equal(result.kind, "reminders"); + return Object.fromEntries( + result.items.map((entry) => [entry.id, entry.status]), + ); +} + +test("notes, untimed tasks, and missing reminder details persist across restart", (t) => { + const path = file(t); + let store = new AssistantStore(path, scope); + try { + assert.equal(statSync(path).mode & 0o777, 0o600); + assert.deepEqual( + store.execute( + source(1), + { kind: "note-add", text: "Plan: ZŁÓŻ wygodny stojak" }, + now, + ), + { kind: "note_saved", id: "N1" }, + ); + assert.deepEqual( + store.execute( + source(2), + { kind: "task-add", text: "Wash the brushes" }, + now, + ), + { kind: "task_added", id: "T1" }, + ); + const first = store.execute( + source(3), + { + kind: "reminder-question", + text: "Bring the brushes", + date: "2030-02-21", + }, + now, + ); + assert.equal(first.item.id, "Q1"); + } finally { + store.close(); + } + store = new AssistantStore(path, scope); + t.after(() => store.close()); + assert.equal( + store.execute(source(1), { kind: "note-add", text: "Replay" }, now), + null, + ); + const notes = store.execute(source(4), { kind: "notes", query: "złóż" }, now); + assert.deepEqual( + notes.items.map((entry) => entry.id), + ["N1"], + ); + assert.deepEqual( + store.execute(source(5), { kind: "notes", query: "%" }, now).items, + [], + ); + const tasks = store.execute(source(6), { kind: "tasks" }, now); + assert.equal(tasks.items[0].dueAt, null); + assert.deepEqual(store.execute(source(7), { kind: "task-done" }, now), { + kind: "task_done", + id: "T1", + }); + assert.deepEqual(store.execute(source(8), { kind: "tasks" }, now).items, []); + const scheduled = store.execute( + source(9), + { kind: "reminder-answer", time: "14:30" }, + now, + ); + assert.equal(scheduled.kind, "reminder_saved"); + assert.equal(scheduled.item.text, "Bring the brushes"); + assert.equal(scheduled.item.dueAt, Date.parse("2030-02-21T13:30:00Z")); + assert.equal( + store.execute(source(9), { kind: "reminder-answer", time: "14:30" }, now), + null, + ); + assert.deepEqual( + store.execute( + source(10), + { kind: "reminder-answer", questionId: "Q1", time: "14:30" }, + now, + ), + { kind: "problem", code: "no_question" }, + ); + assert.deepEqual( + store.execute(source(11), { kind: "questions" }, now).items, + [], + ); + assert.equal( + store.execute(source(12), { kind: "reminders" }, now).items.length, + 1, + ); +}); + +test("independent questions require an explicit selection and reject expired answers", (t) => { + const store = new AssistantStore(file(t), scope); + t.after(() => store.close()); + store.execute( + source(1), + { kind: "reminder-question", text: "Start kiln", date: "2030-02-21" }, + now, + ); + store.execute( + source(2), + { kind: "task-add", text: "Refill the water bottle" }, + now, + ); + store.execute( + source(3), + { kind: "reminder-question", text: "Pack apron", date: "2030-02-22" }, + now, + ); + assert.deepEqual( + store.execute(source(4), { kind: "reminder-answer", time: "18:00" }, now), + { kind: "problem", code: "multiple_questions" }, + ); + assert.deepEqual( + store.execute(source(5), { kind: "question-cancel", id: "Q1" }, now), + { kind: "question_cancelled", id: "Q1" }, + ); + assert.deepEqual( + store.execute( + source(6), + { kind: "reminder-answer", questionId: "Q1", time: "18:00" }, + now, + ), + { kind: "problem", code: "no_question" }, + ); + assert.deepEqual( + store.execute( + source(7), + { kind: "reminder-answer", time: "18:00" }, + Date.parse("2030-02-23T00:00:00Z"), + ), + { kind: "problem", code: "invalid_time" }, + ); + assert.deepEqual( + store + .execute(source(8), { kind: "questions" }, now) + .items.map((item) => item.id), + ["Q2"], + ); + assert.equal( + store.execute( + source(9), + { + kind: "reminder-answer", + questionId: "Q2", + date: "2030-02-24", + time: "18:00", + }, + Date.parse("2030-02-23T00:00:00Z"), + ).kind, + "reminder_saved", + ); +}); + +test("a direct reminder move invalidates a pending question about the old time", (t) => { + const store = new AssistantStore(file(t), scope); + t.after(() => store.close()); + assert.equal(reminder(store, 1).kind, "reminder_saved"); + store.execute( + source(2), + { kind: "reminder-question", id: "R1", date: "2030-02-21" }, + now, + ); + assert.equal( + store.execute( + source(3), + { kind: "reminder-move", id: "R1", dueAt: now + 2 * minute }, + now, + ).item.version, + 2, + ); + assert.deepEqual( + store.execute( + source(4), + { kind: "reminder-answer", questionId: "Q1", time: "18:00" }, + now, + ), + { kind: "problem", code: "no_question" }, + ); +}); + +test("cancel and move invalidate reserved occurrences before dispatch", (t) => { + const path = file(t); + const first = new AssistantStore(path, scope); + const second = new AssistantStore(path, scope); + t.after(() => { + first.close(); + second.close(); + }); + const due = now + minute; + reminder(first, 1); + const claim = first.claimDue(due, minute); + assert.equal(claim.id, "R1"); + assert.equal(second.claimDue(due, minute), null); + assert.equal( + second.execute( + source(2), + { kind: "reminder-move", id: "R1", dueAt: due + minute }, + due, + ).item.version, + 2, + ); + assert.equal(first.beginDelivery(claim, due), false); + assert.equal(second.claimDue(due, minute), null); + const moved = second.claimDue(due + minute, minute); + assert.equal(moved.version, 2); + assert.equal(moved.attempt, 1); + assert.equal( + first.execute( + source(3), + { kind: "reminder-cancel", id: "R1" }, + due + minute, + ).kind, + "reminder_cancelled", + ); + assert.equal(second.beginDelivery(moved, due + minute), false); + assert.equal(first.claimDue(due + minute, minute), null); +}); + +test("reclaiming an abandoned reservation preserves the retry count, but in-flight sends are not replayed", (t) => { + const path = file(t); + const due = now + minute; + let store = new AssistantStore(path, scope); + reminder(store, 1); + const reservation = store.claimDue(due, minute); + store.close(); + store = new AssistantStore(path, scope); + assert.equal(store.claimDue(due + 10_000, minute), null); + const recovered = store.claimDue(due + 31_000, minute); + assert.equal(recovered.attempt, 1); + assert.notEqual(recovered.token, reservation.token); + assert.equal(store.beginDelivery(reservation, due + 31_000), false); + assert.equal(store.beginDelivery(recovered, due + 31_000), true); + assert.deepEqual( + store.execute( + source(2), + { kind: "reminder-cancel", id: "R1" }, + due + 32_000, + ), + { kind: "problem", code: "conflict" }, + ); + store.close(); + store = new AssistantStore(path, scope); + t.after(() => store.close()); + store.recoverDeliveries(due + 60_000); + assert.deepEqual(status(store, 3), { R1: "sending" }); + assert.equal(store.claimDue(due + 152_000, 5 * minute), null); + assert.deepEqual(status(store, 4), { R1: "ambiguous" }); +}); + +test("known failures retry after the specified delay and older undelivered appointments expire", (t) => { + const path = file(t); + const store = new AssistantStore(path, scope); + t.after(() => store.close()); + reminder(store, 1); + reminder(store, 2, now + 4 * minute); + const due = now + 4 * minute; + const first = store.claimDue(due, minute); + assert.equal(first.id, "R2"); + assert.deepEqual(status(store, 3), { R2: "claimed", R1: "expired" }); + assert.equal(store.beginDelivery(first, due), true); + store.finishDelivery(first, { kind: "retry", retryAt: due + 10_000 }, due); + assert.equal(store.claimDue(due + 9_000, minute), null); + const retried = store.claimDue(due + 10_000, minute); + assert.equal(retried.attempt, 2); + assert.equal(store.beginDelivery(retried, due + 10_000), true); + const messageId = source(100); + store.finishDelivery(retried, { kind: "sent", messageId }, due + 11_000); + assert.equal(store.claimDue(due + 12_000, minute), null); + assert.deepEqual(status(store, 4), { R2: "sent", R1: "expired" }); + const inspection = new DatabaseSync(path, { readOnly: true }); + t.after(() => inspection.close()); + assert.equal( + inspection + .prepare("SELECT message_id FROM assistant_outbox WHERE state='sent'") + .get().message_id, + messageId, + ); +}); + +test("unsupported schema or another owner/thread cannot alter existing state", (t) => { + const path = file(t); + const store = new AssistantStore(path, scope); + reminder(store, 1); + store.close(); + assert.throws( + () => new AssistantStore(path, { ...scope, threadId: source(1) }), + /bound to another owner or thread/, + ); + const next = new DatabaseSync(path); + next.exec(`PRAGMA user_version=${ASSISTANT_SCHEMA_VERSION + 1}`); + next.close(); + assert.throws( + () => new AssistantStore(path, scope), + /Unsupported assistant database schema/, + ); + const inspection = new DatabaseSync(path); + t.after(() => inspection.close()); + assert.equal( + inspection.prepare("SELECT count(*) as n FROM assistant_reminders").get().n, + 1, + ); + assert.equal( + inspection.prepare("PRAGMA user_version").get().user_version, + ASSISTANT_SCHEMA_VERSION + 1, + ); +}); + +test("assistant setup does not adopt an existing database with unrelated tables", (t) => { + const path = file(t); + const existing = new DatabaseSync(path); + chmodSync(path, 0o600); + t.after(() => existing.close()); + existing.exec( + "CREATE TABLE jobs(id TEXT); INSERT INTO jobs VALUES ('legacy-task')", + ); + assert.throws( + () => new AssistantStore(path, scope), + /contains unrelated state/, + ); + assert.equal(existing.prepare("PRAGMA user_version").get().user_version, 0); + assert.equal(existing.prepare("SELECT id FROM jobs").get().id, "legacy-task"); +}); diff --git a/apps/discord-agent/test/personal-assistant.test.mjs b/apps/discord-agent/test/personal-assistant.test.mjs new file mode 100644 index 0000000..bfde9ef --- /dev/null +++ b/apps/discord-agent/test/personal-assistant.test.mjs @@ -0,0 +1,155 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { loadAssistantSettings, PersonalAssistant } from "../dist/assistant.js"; +import { ReminderScheduler } from "../dist/assistant-delivery.js"; +import { AssistantStore } from "../dist/assistant-store.js"; + +const config = { + guildId: "111111111111111111", + ownerId: "222222222222222222", + parentId: "333333333333333333", + token: "synthetic-bot-token", +}; +const threadId = "444444444444444444"; +const settings = { + threadId, + locale: "pl", + zone: "Europe/Warsaw", + maxLatenessMs: 360_000, +}; +const discordEpoch = 1_420_070_400_000n; +const now = Date.parse("2027-01-02T10:00:00Z"); +const createMessage = (content, sequence, overrides = {}) => ({ + id: String(((BigInt(now) - discordEpoch) << 22n) + BigInt(sequence)), + guildId: config.guildId, + authorId: config.ownerId, + parentId: config.parentId, + channelId: threadId, + thread: true, + bot: false, + webhook: false, + content, + attachments: 0, + ...overrides, +}); + +test("assistant is opt-in and requires a valid explicit lateness policy", () => { + assert.equal(loadAssistantSettings({}), undefined); + const env = { + PLOMPY_ASSISTANT_THREAD_ID: threadId, + PLOMPY_ASSISTANT_TIME_ZONE: "Europe/Warsaw", + PLOMPY_ASSISTANT_LOCALE: "pl", + PLOMPY_ASSISTANT_MAX_LATE_MINUTES: "6", + }; + assert.deepEqual(loadAssistantSettings(env), settings); + for (const value of ["", "-10", "1441", "1.5"]) + assert.throws(() => + loadAssistantSettings({ + ...env, + PLOMPY_ASSISTANT_MAX_LATE_MINUTES: value, + }), + ); + assert.throws(() => + loadAssistantSettings({ ...env, PLOMPY_ASSISTANT_TIME_ZONE: "Fake/Zone" }), + ); +}); + +test("assistant consumes only its thread, rejects other actors, and persists before reply", async () => { + const store = new AssistantStore(":memory:", { + ...settings, + ownerId: config.ownerId, + }); + try { + const replies = []; + const assistant = new PersonalAssistant( + config, + settings, + store, + { send: async (id, text) => replies.push({ id, text }) }, + () => now, + ); + assert.equal( + await assistant.handle( + createMessage("Zapisz notatkę o stole", 1, { + channelId: "555555555555555555", + }), + ), + false, + ); + for (const overrides of [ + { authorId: "555555555555555555" }, + { parentId: "555555555555555555" }, + { guildId: "555555555555555555" }, + { bot: true }, + { webhook: true }, + ]) { + await assistant.handle( + createMessage("!assistant note Should not be stored", 2, overrides), + ); + } + assert.equal(replies.length, 0); + const note = createMessage( + "Zapisz pomysł do rolki o ponawianiu webhooków", + 3, + ); + await assistant.handle(note); + await assistant.handle(note); + await assistant.handle(createMessage("!assistant notes webhook", 4)); + assert.deepEqual( + replies.map(({ id }) => id), + [threadId, threadId], + ); + assert.match(replies[0].text, /N1/); + assert.match(replies[1].text, /ponawianiu webhooków/); + assert.doesNotMatch(replies[1].text, /Should not/); + } finally { + store.close(); + } +}); + +test("a live question does not block due reminders or prevent another task from being saved", async () => { + const store = new AssistantStore(":memory:", { + ...settings, + ownerId: config.ownerId, + }); + const replies = []; + const deliveries = []; + const assistant = new PersonalAssistant( + config, + settings, + store, + { send: async (_id, text) => replies.push(text) }, + () => now, + ); + const scheduler = new ReminderScheduler( + store, + async (_id, text) => { + deliveries.push(text); + return { kind: "sent", messageId: "666666666666666666" }; + }, + { ...settings, now: () => now + 60_000 }, + ); + try { + await assistant.handle(createMessage("Przypomnij mi jutro o filtrze", 1)); + assert.match(replies[0], /Q1.*O której/); + await assistant.handle(createMessage("Dodaj zadanie: kupić filtr", 2)); + assert.match(replies[1], /T1/); + await assistant.handle( + createMessage("!assistant remind in 1 minute | test zegara", 3), + ); + await scheduler.tick(); + assert.equal(deliveries.length, 1); + assert.match(deliveries[0], /R1.*\n.*test zegara/); + await assistant.handle( + createMessage("18:30", 4, { replyToId: "777777777777777777" }), + ); + assert.match(replies.at(-1), /podaj ID pytania/); + await assistant.handle(createMessage("18:30", 5)); + assert.match(replies.at(-1), /R2.*18:30.*Europe\/Warsaw/); + await assistant.handle(createMessage("Przełóż to na wieczór", 6)); + assert.match(replies.at(-1), /Q2.*Którego dnia i o której godzinie/); + } finally { + await scheduler.stop(); + store.close(); + } +}); diff --git a/docs/architecture.md b/docs/architecture.md index cbcdce8..6f727b0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -98,9 +98,10 @@ these operations. No remote credential or push implementation is included. ## Deliberate limits -One worker; one configured server owner; text and bounded still-image intake; no REST history catch-up; no -scheduler; no built-in public posting destination or receipt broker. Extending these requires -explicit authority checks, durable state and regression tests at the new boundary. +One coding worker, one configured server owner, and text and bounded still-image intake. +The [personal assistant preview](personal-assistant.md) has its own SQLite database and a +timer limited to explicit one-time reminders in the configured owner thread. It does not +read Discord history or schedule runner jobs. ## Provider-bound sessions diff --git a/docs/personal-assistant.md b/docs/personal-assistant.md new file mode 100644 index 0000000..ab1f47a --- /dev/null +++ b/docs/personal-assistant.md @@ -0,0 +1,106 @@ +# Personal assistant preview + +Plompy 1.0.0-alpha.1 can keep notes, tasks, and one-time reminders in a dedicated +thread in the existing private Discord forum. The assistant recognizes built-in +Polish and English phrases and explicit commands. It handles those operations +without sending the conversation to a model or occupying the coding worker. + +## Enable the assistant + +1. Use the supported public engine on Node 26.13.0 or later within Node 26. Verify + compatibility and backups before changing a private fork or its runtime. +2. Create a separate thread in the private forum already configured for Plompy. + Restrict forum access to the owner and bot, and review server administrator + access. The bot must be able to read the thread and send messages. +3. Add the following to the private service environment file. Replace the + synthetic ID and select your locale, IANA time zone, and lateness window. + + ```dotenv + PLOMPY_ASSISTANT_THREAD_ID=555555555555555555 + PLOMPY_ASSISTANT_LOCALE=en + PLOMPY_ASSISTANT_TIME_ZONE=UTC + PLOMPY_ASSISTANT_MAX_LATE_MINUTES=60 + ``` + +4. Start the tested version under the existing instance lock. With Compose, use a + single engine service and set `PLOMPY_IMAGE` to the tested alpha image or build + the alpha checkout. Use the same private environment file as the service. +5. Check the startup event for `"assistant":true`. To test the feature, the + owner can save a synthetic note, ask for a reminder tomorrow, then answer + the follow-up with a time. For a short reminder use + `!assistant remind in 1 minute | Check the test timer`. + +Keep the assistant in its own thread. The server owner and configured forum +are checked using the engine's existing identity settings. The assistant uses +its chosen thread for incoming commands and every delivery, including retries. +Discord mentions are disabled for replies and reminders. + +## Use the thread + +| Request | Explicit form | +| --- | --- | +| Save a note | `!assistant note Ideas for the garden` | +| List or search recent notes | `!assistant notes` or `!assistant notes garden` | +| Add a task without a deadline | `!assistant task Buy a new filter` | +| See open tasks or complete one | `!assistant tasks` or `!assistant done T1` | +| Schedule a reminder | `!assistant remind tomorrow 14:30 \| Change the filter` | +| Move or cancel a reminder | `!assistant move R1 tomorrow 15:00` or `!assistant cancel R1` | +| See reminder and delivery status | `!assistant reminders` | +| See or close unresolved questions | `!assistant questions` or `!assistant question-cancel Q1` | +| Answer a question by ID | `!assistant answer Q1 14:30` or `!assistant answer Q1 2030-06-10 14:30` | + +For example, write “Przypomnij mi jutro o filtrze”. Plompy saves the open +question and asks for a time. Send a new message with “18:30” if exactly one +question is open. Include the question ID when using Discord's Reply button +or when several questions are open. You can add another +task while a question is open. “Zrobione” completes a task if there is exactly +one open task. Use the ID if several tasks are open. + +Relative dates use your time zone and the creation time on the Discord +message. Use a 24-hour time. For a repeated hour at the end of daylight +saving time, give the matching offset explicitly, for example +`02:30 UTC+01:00`. For a skipped hour, choose a different time. + +This preview handles the supported phrases and commands. Lists display up to +12 entries. The command help is always available as `!assistant help`. + +## Delivery and recovery + +The timer checks SQLite every five seconds. When a reminder becomes due, Plompy +claims its current version and checks that it is still valid before beginning +the send attempt. Moving or cancelling it before that transition prevents the +old occurrence from being sent. After the transition, the list shows that a +send attempt has already started. + +- Discord accepting the message records the receipt. The owner can see that + delivery state without relying on the model. +- A definite rate-limit rejection can be retried, up to three total attempts. + An uncertain send or crash during a send becomes **delivery uncertain**. + Check the thread before replacing an uncertain reminder. +- After downtime, reminders within the configured window can still be sent. + Reminders at least one minute late are labeled delayed. Older reminders are + marked overdue and stay available through the reminder list. +- Removing `PLOMPY_ASSISTANT_THREAD_ID` and restarting disables the assistant + and its timer. Its data stays on disk. The public preview only sends reminders + the owner requested. + +## Backup and rollback + +Assistant state lives in `assistant.sqlite` under the private +`PLOMPY_STATE_DIR`. The database identifies its owning Discord thread and +refuses to open under a different owner or thread. Keep it and its sidecars +under the service account's private directory. + +Before switching versions, follow the existing [engine snapshot procedure](state-backups.md) +for `agent.sqlite` and take a separate SQLite online backup of +`assistant.sqlite`, such as with the SQLite CLI's `.backup` command, to a new +private destination. Verify the backup with `PRAGMA integrity_check` and keep +the code, configuration, and compatible state together. The engine snapshot +tool is for the coding database. Copying a main SQLite file while its WAL is +active can omit committed records. + +For rollback, stop the tested release before starting an older release under +the instance lock. Preserve the assistant database for later use. If you +restore an earlier assistant snapshot, reconcile its pending reminders against +the Discord thread before enabling its timer, since some reminders might have +been sent after that snapshot. diff --git a/package.json b/package.json index b82bee2..f2eaa1d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "plompy-engine", - "version": "0.13.0", + "version": "1.0.0-alpha.1", "private": true, "description": "A self-hosted personal agent with Discord conversations and Git-backed memory", "engines": { diff --git a/packages/browser/pyproject.toml b/packages/browser/pyproject.toml index 8503f06..2dc5c4c 100644 --- a/packages/browser/pyproject.toml +++ b/packages/browser/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "plompy-browser" -version = "0.13.0" +version = "1.0.0a1" description = "Persistent Camoufox browser tools over local MCP stdio" requires-python = ">=3.12,<3.15" dependencies = ["camoufox==0.5.9", "mcp==2.3.0"] diff --git a/packages/browser/src/plompy_browser/__init__.py b/packages/browser/src/plompy_browser/__init__.py index 231a2ee..40f8fbc 100644 --- a/packages/browser/src/plompy_browser/__init__.py +++ b/packages/browser/src/plompy_browser/__init__.py @@ -1,3 +1,3 @@ """Plompy's local browser bridge. Importing this package launches nothing.""" -__version__ = "0.13.0" +__version__ = "1.0.0a1" diff --git a/packages/browser/uv.lock b/packages/browser/uv.lock index 351f8c3..57d8728 100644 --- a/packages/browser/uv.lock +++ b/packages/browser/uv.lock @@ -1318,7 +1318,7 @@ wheels = [ [[package]] name = "plompy-browser" -version = "0.13.0" +version = "1.0.0a1" source = { editable = "." } dependencies = [ { name = "camoufox" }, diff --git a/packages/local-mcp/package-lock.json b/packages/local-mcp/package-lock.json index 5c9525a..926662a 100644 --- a/packages/local-mcp/package-lock.json +++ b/packages/local-mcp/package-lock.json @@ -1,12 +1,12 @@ { "name": "@plompy/local-mcp", - "version": "0.13.0", + "version": "1.0.0-alpha.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@plompy/local-mcp", - "version": "0.13.0", + "version": "1.0.0-alpha.1", "license": "MIT", "dependencies": { "@modelcontextprotocol/sdk": "1.32.2", diff --git a/packages/local-mcp/package.json b/packages/local-mcp/package.json index 55e4cac..9fce9b6 100644 --- a/packages/local-mcp/package.json +++ b/packages/local-mcp/package.json @@ -1,6 +1,6 @@ { "name": "@plompy/local-mcp", - "version": "0.13.0", + "version": "1.0.0-alpha.1", "private": true, "type": "module", "engines": { "node": ">=26.13.0 <27" }, diff --git a/scripts/release-metadata.mjs b/scripts/release-metadata.mjs index e1affb1..45a3084 100644 --- a/scripts/release-metadata.mjs +++ b/scripts/release-metadata.mjs @@ -3,18 +3,24 @@ import { appendFileSync, readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { resolve } from 'node:path'; -export function browserVersions({ project, lock }) { +export function browserVersions({ project, lock, initializer }) { const projectVersion = project.match(/^version\s*=\s*"([^"]+)"\s*$/m)?.[1]; const packages = lock.split(/^\[\[package\]\]\s*$/m).slice(1); const browserPackages = packages.filter((entry) => /^name\s*=\s*"plompy-browser"\s*$/m.test(entry)); assert.equal(browserPackages.length, 1, 'uv.lock must contain exactly one plompy-browser project.'); const lockVersion = browserPackages[0].match(/^version\s*=\s*"([^"]+)"\s*$/m)?.[1]; assert(projectVersion && lockVersion, 'Both browser project and uv.lock need a version.'); - return [projectVersion, lockVersion]; + const versions = [projectVersion, lockVersion]; + if (initializer !== undefined) { + const runtimeVersion = initializer.match(/^__version__\s*=\s*"([^"]+)"\s*$/m)?.[1]; + assert(runtimeVersion, 'The browser initializer needs a version.'); + versions.push(runtimeVersion); + } + return versions; } /** Reject malformed tags before they reach a registry, output file, or shell. */ -export function releaseMetadata({ tag, repository, revision, versions }) { +export function releaseMetadata({ tag, repository, revision, versions, browser }) { const identifier = '(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)'; const match = new RegExp(`^v(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-(${identifier}(?:\\.${identifier})*))?$`).exec(tag); assert(match, 'Release tag must be vMAJOR.MINOR.PATCH, optionally with a SemVer prerelease.'); @@ -22,7 +28,16 @@ export function releaseMetadata({ tag, repository, revision, versions }) { assert(/^[a-f0-9]{40}$/.test(revision), 'Release revision must be a full Git commit SHA.'); const version = tag.slice(1); assert(version.length <= 128, 'Release version exceeds the registry tag length.'); - assert(versions.length > 0 && versions.every((value) => value === version), 'Tag, packages, lockfile, and browser versions must agree.'); + assert(versions.length > 0 && versions.every((value) => value === version), 'Tag, packages, and npm lockfile versions must agree.'); + if (browser !== undefined) { + let pythonVersion = match.slice(1, 4).join('.'); + if (match[4]) { + const stage = /^(alpha|beta|rc)\.(0|[1-9][0-9]*)$/.exec(match[4]); + assert(stage, 'Browser prereleases require alpha.N, beta.N, or rc.N in the release tag.'); + pythonVersion += { alpha: 'a', beta: 'b', rc: 'rc' }[stage[1]] + stage[2]; + } + assert(browser.length >= 2 && browser.every((value) => value === pythonVersion), 'Tag and browser versions must agree using canonical PEP 440.'); + } const image = `ghcr.io/${repository.toLowerCase()}`; const tags = [`${image}:${version}`, `${image}:sha-${revision.slice(0, 12)}`]; if (!match[4]) tags.push(`${image}:${match[1]}.${match[2]}`, `${image}:latest`); @@ -47,12 +62,14 @@ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.ur const browser = browserVersions({ project: readFileSync(resolve(root, 'packages/browser/pyproject.toml'), 'utf8'), lock: readFileSync(resolve(root, 'packages/browser/uv.lock'), 'utf8'), + initializer: readFileSync(resolve(root, 'packages/browser/src/plompy_browser/__init__.py'), 'utf8'), }); const result = releaseMetadata({ tag: process.env.RELEASE_TAG, repository: process.env.GITHUB_REPOSITORY, revision: process.env.GITHUB_SHA, - versions: [json('package.json').version, json('apps/discord-agent/package.json').version, lock.version, lock.packages[''].version, json('packages/local-mcp/package.json').version, localLock.version, localLock.packages[''].version, ...browser], + versions: [json('package.json').version, json('apps/discord-agent/package.json').version, lock.version, lock.packages[''].version, json('packages/local-mcp/package.json').version, localLock.version, localLock.packages[''].version], + browser, }); const output = Object.entries({ ...result, local_tags: variantTags(result, 'local'), local_browser_tags: variantTags(result, 'local-browser') }).map(([key, value]) => `${key}=${value}\n`).join(''); if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, output); diff --git a/scripts/release-metadata.test.mjs b/scripts/release-metadata.test.mjs index b8af0af..3ac003a 100644 --- a/scripts/release-metadata.test.mjs +++ b/scripts/release-metadata.test.mjs @@ -33,11 +33,28 @@ test('invalid versions and workflow output injection are rejected', () => { test('the browser lock version participates in release consistency checks', () => { const project = '[project]\nname = "plompy-browser"\nversion = "0.2.0"\n'; const lock = 'version = 1\n\n[[package]]\nname = "dependency"\nversion = "5.0.0"\n\n[[package]]\nname = "plompy-browser"\nversion = "0.2.0"\n'; - assert.deepEqual(browserVersions({ project, lock }), ['0.2.0', '0.2.0']); - assert.throws(() => metadata({ versions: browserVersions({ project, lock: lock.replace('version = "0.2.0"', 'version = "0.1.0"') }) }), /must agree/); + const initializer = '__version__ = "0.2.0"\n'; + const browser = browserVersions({ project, lock, initializer }); + assert.deepEqual(browser, ['0.2.0', '0.2.0', '0.2.0']); + assert.equal(metadata({ browser }).version, '0.2.0'); + assert.throws(() => metadata({ browser: browserVersions({ project, lock: lock.replace('version = "0.2.0"', 'version = "0.1.0"'), initializer }) }), /must agree/); + assert.throws(() => metadata({ browser: browserVersions({ project, lock, initializer: initializer.replace('0.2.0', '0.1.0') }) }), /must agree/); assert.throws(() => browserVersions({ project, lock: '' }), /exactly one/); }); +test('SemVer prereleases and canonical Python versions agree without moving stable tags', () => { + for (const [stage, pythonStage] of [['alpha', 'a'], ['beta', 'b'], ['rc', 'rc']]) { + const version = '1.0.0-' + stage + '.1'; + const pythonVersion = '1.0.0' + pythonStage + '1'; + const result = metadata({ tag: 'v' + version, versions: [version], browser: [pythonVersion, pythonVersion] }); + assert.equal(result.version, version); + assert.equal(result.prerelease, true); + assert.equal(result.tags, 'ghcr.io/owner/engine:' + version + ',ghcr.io/owner/engine:sha-aaaaaaaaaaaa'); + assert.throws(() => metadata({ tag: 'v' + version, versions: [version], browser: [pythonVersion, version] }), /canonical PEP 440/); + } + assert.throws(() => metadata({ tag: 'v1.0.0-preview.1', versions: ['1.0.0-preview.1'], browser: ['1.0.0a1', '1.0.0a1'] }), /Browser prereleases require/); +}); + test('local variants retain exact and architecture-independent revision tags without moving engine aliases', () => { const result = metadata();