Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Bring added organization teams up to a newer release, keeping the person's changes (#4380)
Azad Jagtap7a16a7eea972
diff --git a/docs/org-library.md b/docs/org-library.mdindex 858f4b1a2d..4a7ff479f9 100644--- a/docs/org-library.md+++ b/docs/org-library.md@@ -45,15 +45,46 @@ Compared with a file:A bot added from the organization's library shows where it came from in**Bot settings → Identity**: "From Sales desk 1.3.0 · Acme Partners". A bot-imported from a file shows no such line, as before. This version never-changes something it already added. When the catalog names a newer release,-the card says "Version X available. Updates arrive automatically in an-upcoming OpenMausBot update."+imported from a file shows no such line, as before. When the catalog names+a newer release of an added team, it comes over on its own (see Updates+below). Until its file is downloaded, the card says "Version X available. It+comes over on its own once it's downloaded, and keeps your changes."**Required** is treated as Available in this version, with a "Recommendedby …" badge. Entries the organization switched **off** are hidden, andtheir copies stay.+## Updates++After each relayed catalog, every added team whose catalog release differs+from the one it has is brought up to that release, once its file is+downloaded and readable by this app (`server/org-library-releases.ts`). A+release listed under `withdrawnReleases` is never moved to, and a withdrawn+or removed install is left alone.++It goes part by part, by the `r` and `w` hashes stamped when each part was+written. A part takes the new release's value only when the publisher changed+it (its new hash is not `r`) and the person did not (the part as it is now+still hashes to `w`). It is then written and stamped with the new hash. A part+the person changed keeps their version, now and in later releases.++| Part | Updated |+|---|---|+| A bot's name, title, description, instructions and playbooks | yes; a new name another bot already has is kept back |+| A bot's skills | each skill's text, and a skill new to that bot in this release (while the file of the release it had is still kept, which is how a new skill is told from one the person took off); never one the person took off, and a skill switched off stays off |+| A group chat's name and bulletin | yes |+| A routine's name, prompt and schedule | yes; whether it is on stays the person's |+| The team brief | yes |+| Look, connections, approval, room members and responder, routine targets, the leader | not in this version: they stay as they were added |+| Bots, group chats and routines new in a release | not added in this version |++An update never raises approval, switches a routine on, or adds a+connection. The install, each bot's `installedPackage` and each updated+skill's stamp move to the new release. If a part can't be written, the parts+written so far keep their new stamps, the install stays on its release, and+the next catalog finishes it; a skill whose new text can't be written is put+back as it was.+## Withdrawn releasesWhen the catalog lists an added release under `withdrawnReleases`, its@@ -154,9 +185,9 @@ are gone the install is `removed` and **Add** brings the whole team back.Each install's `removedLocally` (contract §3.4) lists the parts of an addedteam the person deleted: `agent:<key>` for a bot, `room:<key>` for a group-chat and `routine:<key>` for a routine. The automatic update (v1.1) reads it-to tell a part the person deleted from a part a new release adds, and never-brings a deleted part back. It is kept like this:+chat and `routine:<key>` for a routine. It tells a part the person deleted+from a part a new release adds, so an update never brings a deleted part+back. It is kept like this:- **When it is noted.** Each time the index is rebuilt, a key the index heldthat no longer has a record is added to the list once. Rebuilding again,@@ -214,9 +245,10 @@ starts with `OMB_TEST_ORG_LIBRARY_KEY`, and the request carries that key in## Not in this version-These arrive in v1.1 with no format change:+These arrive later with no format change:-- automatic updates;+- updating a bot's look, connections and approval, room members, routine+ targets and the leader, and adding parts new in a release;- Required with auto-install;- honouring `offAction: "remove"`;- the Admin Withdraw button.diff --git a/server/index.ts b/server/index.tsindex e3a1b4419b..b9e086bdc5 100644--- a/server/index.ts+++ b/server/index.ts@@ -354,7 +354,7 @@ import {readSections,sectionContextKey,sectionContextSystemPrompt,- writeSectionContext,+ readSectionContext, writeSectionContext,} from "./section-context.ts";import {applyStagedSkillWrite,@@ -366,7 +366,7 @@ import {scanSkillText,listSkills,listStagedSkillWrites,- readSkillFile,+ readSkillFile, removeSkill,rejectStagedSkillWrite,setSkillEnabled,skillPackageStamps,@@ -9000,8 +9000,8 @@ orgLibrary = new OrgLibrary({dataDir: DATA_DIR,store,routines: routines!,- skills: { list: listSkills, stamps: skillPackageStamps, setEnabled: setSkillEnabled, installOrg: installOrgSkill },- presets: presetStore,+ skills: { list: listSkills, stamps: skillPackageStamps, setEnabled: setSkillEnabled, installOrg: installOrgSkill, read: readSkillFile, remove: removeSkill },+ presets: presetStore, sections: { read: (section) => readSectionContext(section)?.text ?? "", write: (section, text) => void writeSectionContext(section, text) },postState: (message) => utilityParentPort?.postMessage(message),});{diff --git a/server/org-library-releases.ts b/server/org-library-releases.tsnew file mode 100644index 0000000000..f7cf1b74a9--- /dev/null+++ b/server/org-library-releases.ts@@ -0,0 +1,260 @@+// What a newer or withdrawn release in the organization's catalog does to an install, after each relayed catalog.+//+// An update goes part by part, by the two hashes stamped on each part when it was written: `r`, the part as released,+// and `w`, the part as written here. A part changes only when the publisher changed it (the new release's hash is not+// `r`) and the person did not (the part as it is now still hashes to `w`); it is then written and stamped `r` = `w` =+// the new hash. A part the person edited is kept as they left it, and its stamp is left alone, so it stays theirs.+// Security: an update never raises approval, switches a routine on, or adds a connection or its values.+import type { PackageAgent, PackageDocument } from "../shared/package-format.ts";+import type { OrgInstall, OrgLibraryDeps, OrgLibraryEntry } from "./org-library.ts";+import {+ agentReleaseValues, pair, partHash, playbookValues, roomReleaseValues, routineReleaseValues, scheduleValue,+ type AgentPart, type PartPair, type RoomPart, type RoutinePart,+} from "./package-parts.ts";+import type { BotRecord, GroupRecord } from "./store.ts";++export interface ReleaseContext {+ installs: Record<string, OrgInstall>;+ entries: readonly OrgLibraryEntry[];+ /** The install id this organization gives a package; another organization's installs are never touched. */+ currentInstallId(packageId: string): string | null;+ /** The entry's release, read and checked; null while it is not downloaded, or needs a newer app. */+ releaseDocument(entry: OrgLibraryEntry): PackageDocument | null;+ /** The release the install has now, while its file is still kept. */+ installedDocument(install: OrgInstall): PackageDocument | null;+ deps: OrgLibraryDeps;+ now(): number;+}++export function handleWithdrawn(context: ReleaseContext): boolean {+ let changed = false;+ for (const [installId, install] of Object.entries(context.installs)) {+ if (context.currentInstallId(install.packageId) !== installId) continue;+ if (install.status === "withdrawn" || (install.status === "removed" && install.withdrawnHandled === install.sha256)) continue;+ const entry = context.entries.find((candidate) => candidate.packageId === install.packageId);+ if (!entry?.withdrawnReleases.some((withdrawn) => withdrawn.sha256 === install.sha256)) continue;+ switchOff(context.deps, installId);+ if (install.status === "installed") install.status = "withdrawn";+ else install.withdrawnHandled = install.sha256;+ install.updatedAt = context.now();+ changed = true;+ }+ return changed;+}++function switchOff(deps: OrgLibraryDeps, installId: string): void {+ for (const bot of deps.store.bots) {+ for (const skill of deps.skills.stamps(bot.id)) {+ if (skill.stamp.installId !== installId || !skill.enabled) continue;+ const result = deps.skills.setEnabled(bot.id, skill.name, false);+ if ("error" in result) console.warn(`[org-library] could not switch off ${skill.name}: ${result.error}`);+ }+ }+ for (const bot of deps.store.bots) {+ const made = bot.installedPackage;+ if (made?.source !== "org" || made.installId !== installId || !made.presetKey || !made.ref) continue;+ const source = `org:${made.ref}@${made.release}`;+ for (const skill of deps.skills.list(bot.id)) {+ if (skill.source !== source || !skill.enabled) continue;+ const result = deps.skills.setEnabled(bot.id, skill.name, false);+ if ("error" in result) console.warn(`[org-library] could not switch off ${skill.name}: ${result.error}`);+ }+ }+ for (const routine of deps.routines.packageStamps()) {+ if (routine.stamp.installId !== installId || !routine.enabled) continue;+ try {+ deps.routines.update(routine.routineId, { enabled: false });+ } catch (error) {+ console.warn(`[org-library] could not pause a routine: ${error instanceof Error ? error.message : String(error)}`);+ }+ }+}++/** Brings each added team up to its catalog release; the ids of the installs it moved to a new release. */+export function applyUpdates(context: ReleaseContext): string[] {+ const updated: string[] = [];+ for (const [installId, install] of Object.entries(context.installs)) {+ if (context.currentInstallId(install.packageId) !== installId || install.status !== "installed" || install.kind !== "team") continue;+ const entry = context.entries.find((candidate) => candidate.packageId === install.packageId);+ const release = entry?.release;+ if (!entry || !release || release.sha256 === install.sha256) continue;+ if (entry.withdrawnReleases.some((withdrawn) => withdrawn.sha256 === release.sha256)) continue;+ const next = context.releaseDocument(entry);+ if (!next) continue;+ const update = new InstallUpdate(context.deps, installId, install, next, release.sha256, context.installedDocument(install));+ try {+ update.bots();+ update.rooms();+ update.routines();+ update.brief();+ } catch (error) {+ // The parts written so far carry their new stamps, so the next catalog picks up from here.+ console.warn(`[org-library] could not finish updating ${install.name || install.packageId}: ${error instanceof Error ? error.message : String(error)}`);+ continue;+ }+ install.release = release.version;+ install.sha256 = release.sha256;+ install.updatedAt = context.now();+ updated.push(installId);+ }+ return updated;+}++/** The parts the update writes; the others stay as they were added (see docs/org-library.md). */+const AGENT_UPDATED = ["name", "title", "description", "soul", "playbooks"] as const satisfies readonly AgentPart[];+const ROOM_UPDATED = ["name", "bulletin"] as const satisfies readonly RoomPart[];+const ROUTINE_UPDATED = ["name", "prompt", "schedule"] as const satisfies readonly RoutinePart[];++/** Whether a part should take the new release's value: the publisher changed it and the person did not. */+function takesRelease(stamp: PartPair | undefined, released: unknown, now: unknown): stamp is PartPair {+ return Boolean(stamp) && partHash(released) !== stamp!.r && partHash(now) === stamp!.w;+}++class InstallUpdate {+ private readonly deps: OrgLibraryDeps;+ private readonly installId: string;+ private readonly install: OrgInstall;+ private readonly pkg: PackageDocument["package"];+ private readonly sha256: string;+ private readonly previous: PackageDocument | null;+ private readonly ref: string;++ constructor(deps: OrgLibraryDeps, installId: string, install: OrgInstall, next: PackageDocument, sha256: string, previous: PackageDocument | null) {+ this.deps = deps;+ this.installId = installId;+ this.install = install;+ this.pkg = next.package;+ this.sha256 = sha256;+ this.previous = previous;+ this.ref = install.ref;+ }++ bots(): void {+ const playbookByKey = new Map((this.pkg.playbooks ?? []).map((playbook) => [playbook.key, playbook]));+ for (const agent of this.pkg.agents) {+ const bot = this.deps.store.bot(this.install.bots[agent.key] ?? "");+ if (!bot?.packageBase) continue;+ const released = agentReleaseValues(agent, playbookByKey);+ const now: Record<(typeof AGENT_UPDATED)[number], unknown> = {+ name: bot.name, title: bot.title ?? "", description: bot.description ?? "", soul: bot.soul ?? "", playbooks: playbookValues(bot.playbooks ?? []),+ };+ const base: Partial<Record<AgentPart, PartPair>> = { ...bot.packageBase };+ const profile: Partial<Pick<BotRecord, "name" | "title" | "description" | "soul">> = {};+ let playbooks: BotRecord["playbooks"] | undefined;+ for (const part of AGENT_UPDATED) {+ if (!takesRelease(base[part], released[part], now[part])) continue;+ if (part === "name" && this.nameTaken(bot.id, String(released.name))) continue;+ if (part === "playbooks") playbooks = (agent.playbooks ?? []).flatMap((key) => (playbookByKey.has(key) ? [{ ...playbookByKey.get(key)! }] : []));+ else profile[part] = String(released[part]);+ base[part] = pair(released[part], part === "playbooks" ? playbookValues(playbooks ?? []) : released[part]);+ }+ if (this.skills(bot, agent)) base.skills = pair(released.skills, released.skills);+ if (Object.keys(profile).length) this.deps.store.patchBotProfile(bot.id, profile);+ const installed = bot.installedPackage && { ...bot.installedPackage, release: this.pkg.release, sha256: this.sha256 };+ // The stamps go last: a part written before a crash and not yet stamped is kept, never written twice.+ this.deps.store.patchBot(bot.id, { ...(playbooks ? { playbooks } : {}), packageBase: base, ...(installed ? { installedPackage: installed } : {}) });+ }+ }++ /** Each skill the publisher changed and the person did not gets the new text; a skill new in this release is added, but+ * never one the person took off. Whether a skill is on is the person's and stays. */+ private skills(bot: BotRecord, agent: PackageAgent): boolean {+ const entries = new Map((this.pkg.skills?.entries ?? []).map((skill) => [skill.name, skill]));+ const stamped = new Map(this.deps.skills.stamps(bot.id).filter((skill) => skill.stamp.installId === this.installId).map((skill) => [skill.stamp.key, skill]));+ const before = this.previous?.package.agents.find((candidate) => candidate.key === agent.key)?.skills;+ const source = `org:${this.ref}@${this.pkg.release}`;+ let changed = false;+ for (const name of agent.skills ?? []) {+ const skill = entries.get(name);+ if (!skill) continue;+ const stamp = { installId: this.installId, key: name, release: this.pkg.release, ...pair(skill.instructions, skill.instructions) };+ const have = stamped.get(name);+ if (have) {+ if (partHash(skill.instructions) === have.stamp.r || !this.deps.skills.read || !this.deps.skills.remove) continue;+ const text = this.deps.skills.read(bot.id, name);+ if (text === null || partHash(text) !== have.stamp.w) continue;+ const was = this.deps.skills.list(bot.id).find((listed) => listed.name === name)?.source ?? source;+ if ("error" in this.deps.skills.remove(bot.id, name)) continue;+ const added = this.deps.skills.installOrg(bot.id, source, skill.instructions, stamp);+ if ("error" in added) {+ // Put the skill back as it was, so it is never mistaken later for one the person took off.+ this.deps.skills.installOrg(bot.id, was, text, have.stamp);+ if (!have.enabled) this.deps.skills.setEnabled(bot.id, name, false);+ throw new Error(`skill ${name} could not be updated: ${added.error}`);+ }+ if (!have.enabled) this.deps.skills.setEnabled(bot.id, name, false);+ changed = true;+ } else if (before && !before.includes(name) && !this.deps.skills.list(bot.id).some((listed) => listed.name === name)) {+ const added = this.deps.skills.installOrg(bot.id, source, skill.instructions, stamp);+ if ("error" in added) throw new Error(`skill ${name} could not be added: ${added.error}`);+ changed = true;+ }+ }+ return changed;+ }++ rooms(): void {+ for (const room of this.pkg.rooms ?? []) {+ const group = this.deps.store.group(this.install.rooms[room.key] ?? "");+ const stamp = group?.installedPackage;+ if (!group || !stamp || stamp.installId !== this.installId) continue;+ const released = roomReleaseValues(room);+ const now: Record<(typeof ROOM_UPDATED)[number], unknown> = { name: group.name, bulletin: group.bulletin ?? "" };+ const parts = { ...stamp.parts };+ const patch: Partial<Pick<GroupRecord, "name" | "bulletin">> = {};+ for (const part of ROOM_UPDATED) {+ if (!takesRelease(parts[part], released[part], now[part])) continue;+ patch[part] = String(released[part]);+ parts[part] = pair(released[part], released[part]);+ }+ if (Object.keys(patch).length) this.deps.store.patchGroup(group.id, { ...patch, installedPackage: { ...stamp, parts } });+ }+ }++ routines(): void {+ if (!this.deps.routines.stampInstalledPackage) return;+ const stamps = new Map(this.deps.routines.packageStamps().map((routine) => [routine.routineId, routine.stamp]));+ for (const released of this.pkg.routines ?? []) {+ const id = this.install.routines[released.key] ?? "";+ const stamp = stamps.get(id);+ const routine = this.deps.routines.listRoutines().find((candidate) => candidate.id === id);+ if (!stamp || !routine || stamp.installId !== this.installId) continue;+ const values = routineReleaseValues(released);+ const now: Record<(typeof ROUTINE_UPDATED)[number], unknown> = { name: routine.name, prompt: routine.prompt, schedule: scheduleValue(routine) };+ const take = ROUTINE_UPDATED.filter((part) => takesRelease(stamp.parts[part], values[part], now[part]));+ if (!take.length) continue;+ const timeoutMinutes = released.timeoutMinutes === undefined ? undefined : Math.min(240, Math.max(5, released.timeoutMinutes));+ const updated = this.deps.routines.update(id, {+ ...(take.includes("name") ? { name: released.name } : {}),+ ...(take.includes("prompt") ? { prompt: released.prompt } : {}),+ ...(take.includes("schedule") ? {+ runOn: released.runOn, schedule: released.schedule, durationMinutes: released.durationMinutes,+ ...(timeoutMinutes === undefined ? {} : { timeoutMinutes }),+ ...(released.overlap ? { overlap: released.overlap } : {}),+ ...(released.continuity && released.room === undefined ? { continuity: true } : {}),+ ...(released.runOnStartup ? { runOnStartup: true } : {}),+ } : {}),+ });+ if (!updated) continue;+ const written: Record<(typeof ROUTINE_UPDATED)[number], unknown> = { name: updated.name, prompt: updated.prompt, schedule: scheduleValue(updated) };+ const parts = { ...stamp.parts };+ for (const part of take) parts[part] = pair(values[part], written[part]);+ this.deps.routines.stampInstalledPackage(id, { ...stamp, parts });+ }+ }++ brief(): void {+ const stamp = this.install.team?.parts.brief;+ const sections = this.deps.sections;+ if (!stamp || !sections || !this.install.section) return;+ const released = this.pkg.team?.brief ?? "";+ if (!takesRelease(stamp, released, sections.read(this.install.section))) return;+ sections.write(this.install.section, released);+ this.install.team!.parts.brief = pair(released, released);+ }++ private nameTaken(botId: string, name: string): boolean {+ const wanted = name.trim().toLowerCase();+ return this.deps.store.bots.some((other) => other.id !== botId && other.name.trim().toLowerCase() === wanted);+ }+}diff --git a/server/org-library.e2e.test.ts b/server/org-library.e2e.test.tsindex 9b32e67bf0..901dd8f001 100644--- a/server/org-library.e2e.test.ts+++ b/server/org-library.e2e.test.ts@@ -13,9 +13,10 @@ const PUBLISHER = "33333333-3333-4333-8333-333333333333";const TEAM_ID = "22222222-2222-4222-8222-222222222222";const LIBRARY_ID = "44444444-4444-4444-8444-444444444444";-function release(name: string) {+function release(name: string, edit?: (document: any) => void) {const document: any = parsePackageDocument(JSON.parse(readFileSync(join(FIXTURES, name), "utf8")), { trust: "file" });document.package.publisher = { organization: "acme", name: "Acme Partners" };+ edit?.(document);const bytes = canonicalJson(document);return { document, bytes, sha256: sha(bytes) };}@@ -104,3 +105,52 @@ it("shows the organization's shelf, adds a team once, and keeps its stamps off tawait fixture.close();}}, 120_000);++it("brings an added team to a newer release, keeping what the person changed", async () => {+ const key = randomBytes(32).toString("hex");+ const fixture = await launchVerificationServer({ ...process.env, OMB_TEST_ORG_LIBRARY_KEY: key });+ const url = fixture.info.url;+ const call = async (method: string, path: string, body?: unknown, headers: Record<string, string> = {}) => {+ const response = await fetch(`${url}${path}`, {+ method, headers: { "content-type": "application/json", ...headers }, ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ return { status: response.status, body: await response.json() as any };+ };+ const blobs = join(fixture.info.dataDir, "org-library", "blobs");+ const offer = async (rel: ReturnType<typeof release>, libraryVersion: number) => {+ mkdirSync(blobs, { recursive: true });+ writeFileSync(join(blobs, `${rel.sha256}.json`), rel.bytes, { mode: 0o600 });+ const catalog = JSON.stringify({ format: "openmaus.org-library", version: 1, libraryVersion, organization: { id: ORG, name: "Customer Co" }, packages: [entry(TEAM_ID, rel)] });+ const relayed = await call("POST", "/api/testing/org-library", {+ library: { adminOrigin: "https://admin.example.com", organizationId: ORG, organizationName: "Customer Co", digest: sha(catalog), catalog },+ }, { "x-openmausbot-test-org-library": key });+ expect(relayed.status).toBe(200);+ return relayed.body.report;+ };+ try {+ await offer(release("full-team.v2.json"), 1);+ const added = await call("POST", "/api/org-library/add", { packageId: TEAM_ID });+ expect(added.status).toBe(201);+ const bots = async () => (await call("GET", "/api/bots")).body.bots.filter((bot: any) => bot.section === "Sales desk");+ const byKey = async (agentKey: string) => (await bots()).find((bot: any) => bot.installedPackage.agentKey === agentKey);+ const scout = await byKey("scout");+ expect((await call("PATCH", `/api/bots/${scout.id}`, { soul: "Scout the way we like it." })).status).toBe(200);++ const next = release("full-team.v2.json", (document) => {+ document.package.release = "1.4.0";+ for (const agent of document.package.agents) agent.soul = `${agent.soul} Version two.`;+ });+ const report = await offer(next, 2);+ expect(report.packages).toEqual([{ packageId: TEAM_ID, release: "1.4.0", sha256: next.sha256, state: "installed" }]);+ expect((await byKey("lead")).soul).toMatch(/Version two\.$/);+ expect((await byKey("scout")).soul).toBe("Scout the way we like it.");+ expect((await byKey("lead")).installedPackage).toMatchObject({ release: "1.4.0", sha256: next.sha256 });+ expect(JSON.stringify((await call("GET", "/api/bots")).body)).not.toContain("packageBase");+ expect((await call("GET", "/api/routines")).body.routines.every((routine: any) => !routine.enabled)).toBe(true);+ const shelf = (await call("GET", "/api/org-library")).body.packages[0];+ expect(shelf.installed).toMatchObject({ release: "1.4.0", status: "installed" });+ } finally {+ await fixture.close();+ }+}, 120_000);+diff --git a/server/org-library.test.ts b/server/org-library.test.tsindex 298982c938..4512496cbf 100644--- a/server/org-library.test.ts+++ b/server/org-library.test.ts@@ -110,11 +110,12 @@ async function installation(from?: string) {};const posted: any[] = [];const stamps = vi.fn(skills.skillPackageStamps);- const open = () => new OrgLibrary({+ const open = (over: { read?: (botId: string, name: string) => string | null; installOrg?: typeof skills.installOrgSkill } = {}) => new OrgLibrary({dataDir: DATA_DIR,store,routines,- skills: { list: skills.listSkills, stamps, setEnabled: skills.setSkillEnabled, installOrg: skills.installOrgSkill },+ skills: { list: skills.listSkills, stamps, setEnabled: skills.setSkillEnabled, installOrg: over.installOrg ?? skills.installOrgSkill, read: over.read ?? skills.readSkillFile, remove: skills.removeSkill },+ sections: { read: (section) => sections.readSectionContext(section)?.text ?? "", write: (section, text) => void sections.writeSectionContext(section, text) },presets: presetStore,postState: (message) => posted.push(structuredClone(message)),});@@ -942,3 +943,143 @@ describe("presets from the shelf", () => {expect(app.skills.listSkills(made.id)[0]!.enabled).toBe(true);});});++describe("a newer release of an added team", () => {+ const NEXT = (document: any) => {+ const pkg = document.package;+ pkg.release = "1.4.0";+ const lead = pkg.agents.find((agent: any) => agent.key === "lead");+ lead.soul = "You run the desk. Quote the 2027 price list.";+ lead.title = "Desk lead";+ pkg.playbooks[0].instructions = `${pkg.playbooks[0].instructions} Then confirm the seat count.`;+ pkg.skills.entries.find((skill: any) => skill.name === "pricing-policy").instructions += "\nSeats are 59 from January.";+ pkg.rooms[0].bulletin = "Cite sources. Lead answers first.";+ pkg.routines.find((routine: any) => routine.key === "daily-digest").prompt = "Summarise yesterday's deals, biggest first.";+ pkg.team.brief = "We sell a team plan at 59 per seat.";+ };++ async function addedTeam(over: Parameters<Awaited<ReturnType<typeof installation>>["open"]>[0] = {}) {+ const app = await installation();+ const library = app.open(over);+ const first = release("full-team.v2.json");+ app.writeBlob(first.bytes);+ library.applyRelay(relay(catalog([entry(TEAM_ID, first)])));+ await library.settled();+ const added = library.add(TEAM_ID, app.importDeps) as any;+ const botOf = (key: string) => app.store.bots.find((bot) => bot.installedPackage?.agentKey === key)!;+ const routineOf = (key: string) => app.routines.packageStamps().find((routine) => routine.stamp.key === key)!;+ const update = async (next = release("full-team.v2.json", NEXT), patch: Record<string, unknown> = {}, write = true) => {+ if (write) app.writeBlob(next.bytes);+ library.applyRelay(relay(catalog([entry(TEAM_ID, next, patch)], { libraryVersion: 4 })));+ await library.settled();+ return next;+ };+ return { app, library, first, installId: added.value.result.installId as string, botOf, routineOf, update };+ }++ it("takes every part the publisher changed and the person did not, and moves the install to the new release", async () => {+ const { app, library, installId, botOf, routineOf, update } = await addedTeam();+ const before = botOf("lead");+ const next = await update();+ const lead = botOf("lead");+ expect(lead).toMatchObject({ soul: "You run the desk. Quote the 2027 price list.", title: "Desk lead", name: before.name });+ expect(lead.approvalMode, "an update never raises approval").toBe(before.approvalMode);+ expect(lead.playbooks![0]!.instructions).toMatch(/Then confirm the seat count\.$/);+ expect(lead.installedPackage).toMatchObject({ release: "1.4.0", sha256: next.sha256 });+ expect(app.skills.readSkillFile(lead.id, "pricing-policy")).toMatch(/Seats are 59 from January\./);+ expect(app.skills.skillPackageStamps(lead.id).find((skill) => skill.name === "pricing-policy")!.stamp.release).toBe("1.4.0");+ expect(app.store.groups[0]!.bulletin).toBe("Cite sources. Lead answers first.");+ const daily = app.routines.listRoutines().find((routine) => routine.id === routineOf("daily-digest").routineId)!;+ expect(daily).toMatchObject({ prompt: "Summarise yesterday's deals, biggest first.", enabled: false });+ expect(app.sections.readSectionContext(lead.section)?.text).toBe("We sell a team plan at 59 per seat.");+ expect(app.readState().installs[installId]).toMatchObject({ release: "1.4.0", sha256: next.sha256, status: "installed" });+ expect(app.posted.at(-1).packages).toEqual([{ packageId: TEAM_ID, release: "1.4.0", sha256: next.sha256, state: "installed" }]);+ expect(library.list().packages[0]!.installed).toMatchObject({ release: "1.4.0" });++ // Nothing changes when the same catalog comes again.+ const stamped = structuredClone(botOf("lead").packageBase);+ await update(next);+ expect(botOf("lead").packageBase).toEqual(stamped);+ });++ it("keeps every part the person changed, and takes the rest", async () => {+ const edited = "My own pricing notes.";+ const { app, botOf, routineOf, update } = await addedTeam({ read: (botId, name) => (name === "pricing-policy" ? edited : app.skills.readSkillFile(botId, name)) });+ const lead = botOf("lead");+ app.store.patchBotProfile(lead.id, { soul: "My own instructions." });+ app.store.patchGroup(app.store.groups[0]!.id, { bulletin: "Our own room rules." });+ const daily = routineOf("daily-digest").routineId;+ app.routines.update(daily, { prompt: "My own digest.", enabled: true });+ await update();+ const after = botOf("lead");+ expect(after.soul).toBe("My own instructions.");+ expect(after.title).toBe("Desk lead");+ expect(app.skills.readSkillFile(after.id, "pricing-policy")).not.toMatch(/Seats are 59/);+ expect(app.store.groups[0]!.bulletin).toBe("Our own room rules.");+ expect(app.routines.listRoutines().find((routine) => routine.id === daily)).toMatchObject({ prompt: "My own digest.", enabled: true });++ // A later release that changes the soul again still leaves the person's version alone.+ await update(release("full-team.v2.json", (document) => { NEXT(document); document.package.release = "1.5.0"; document.package.agents[0].soul = "Third version."; }));+ expect(botOf("lead").soul).toBe("My own instructions.");+ });++ it("adds a skill new to a bot in this release, never one the person took off, and keeps a skill switched off", async () => {+ const { app, botOf, update } = await addedTeam();+ const lead = botOf("lead");+ const scout = botOf("scout");+ app.skills.setSkillEnabled(lead.id, "pricing-policy", false);+ const scoutHad = app.skills.listSkills(scout.id).map((skill) => skill.name);+ app.skills.removeSkill(scout.id, scoutHad[0]!);+ await update(release("full-team.v2.json", (document) => {+ NEXT(document);+ document.package.agents.find((agent: any) => agent.key === "lead").skills.push("objection-handling");+ }));+ expect(app.skills.listSkills(lead.id).map((skill) => [skill.name, skill.enabled]).sort()).toEqual([["objection-handling", true], ["pricing-policy", false]]);+ expect(app.skills.readSkillFile(lead.id, "pricing-policy")).toMatch(/Seats are 59 from January\./);+ expect(app.skills.listSkills(scout.id).map((skill) => skill.name)).not.toContain(scoutHad[0]);+ });++ it("puts a skill back when its new text can't be written, and finishes the update with the next catalog", async () => {+ let fail = false;+ const { app, installId, botOf, update } = await addedTeam({+ installOrg: (...args) => {+ if (fail && args[2].includes("Seats are 59")) { fail = false; return { error: "disk full" }; }+ return app.skills.installOrgSkill(...args);+ },+ });+ const lead = botOf("lead");+ const original = app.skills.readSkillFile(lead.id, "pricing-policy");+ fail = true;+ const next = await update();+ expect(app.skills.readSkillFile(lead.id, "pricing-policy")).toBe(original);+ expect(app.readState().installs[installId].release, "not moved while a part failed").toBe("1.3.0");+ await update(next);+ expect(app.skills.readSkillFile(lead.id, "pricing-policy")).toMatch(/Seats are 59 from January\./);+ expect(app.readState().installs[installId].release).toBe("1.4.0");+ });++ it("waits while the new release isn't downloaded or needs a newer app, and never moves to a withdrawn one", async () => {+ const { app, installId, botOf, update } = await addedTeam();+ const soul = botOf("lead").soul;+ const next = await update(undefined, {}, false);+ expect(botOf("lead").soul).toBe(soul);+ expect(app.readState().installs[installId].release).toBe("1.3.0");+ await update(next, { release: { ...entry(TEAM_ID, next).release, formatVersion: 99 } });+ expect(app.readState().installs[installId].release).toBe("1.3.0");+ await update(next, { withdrawnReleases: [{ version: "1.4.0", sha256: next.sha256 }] });+ expect(botOf("lead").soul).toBe(soul);+ expect(app.readState().installs[installId].release).toBe("1.3.0");+ });++ it("leaves a team another organization added, and a removed team, alone", async () => {+ const { app, library, installId, botOf } = await addedTeam();+ const next = release("full-team.v2.json", NEXT);+ app.writeBlob(next.bytes);+ const soul = botOf("lead").soul;+ library.applyRelay(relay({ ...catalog([entry(TEAM_ID, next)]), organization: { id: OTHER_ORG, name: "Other Co" } }, { organizationId: OTHER_ORG }));+ await library.settled();+ expect(botOf("lead").soul).toBe(soul);+ expect(app.readState().installs[installId].release).toBe("1.3.0");+ });+});+diff --git a/server/org-library.ts b/server/org-library.tsindex 10d0508d62..1b1b65d278 100644--- a/server/org-library.ts+++ b/server/org-library.ts@@ -21,6 +21,7 @@ import {} from "./package-import.ts";import { pair, partHash, sha256Hex, type PartPair, type TeamPart } from "./package-parts.ts";import { storedPresetObject, type StoredPreset } from "./presets.ts";+import { applyUpdates, handleWithdrawn, type ReleaseContext } from "./org-library-releases.ts";import type { RoutineManager } from "./routines.ts";import type { SkillListing, SkillPackageStamp } from "./skills.ts";import { sectionKey, type InstalledPackageMetadata, type Store, type StoreChange } from "./store.ts";@@ -242,13 +243,18 @@ function noteRemovedParts(install: OrgInstall, next: Pick<LiveRecords, "bots" |export interface OrgLibraryDeps {dataDir: string;store: Store;- routines: Pick<RoutineManager, "packageStamps" | "update" | "listRoutines" | "remove">;+ routines: Pick<RoutineManager, "packageStamps" | "update" | "listRoutines" | "remove"> & Partial<Pick<RoutineManager, "stampInstalledPackage">>;skills: {list(botId: string): SkillListing[];stamps(botId: string): Array<{ name: string; enabled: boolean; stamp: SkillPackageStamp }>;setEnabled(botId: string, name: string, enabled: boolean): SkillListing | { error: string };installOrg(botId: string, source: string, skillMd: string, stamp: SkillPackageStamp): SkillListing | { error: string };+ /** An update replaces a skill's text only through these; without them skills keep the text they were added with. */+ read?(botId: string, name: string): string | null;+ remove?(botId: string, name: string): { removed: true } | { error: string };};+ /** A team's brief, by its section; without it an update leaves the brief as it is. */+ sections?: { read(section: string): string; write(section: string, text: string): void };postState?: (message: OrgLibraryStateMessage) => void;now?: () => number;presets?: { list(): StoredPreset[] };@@ -380,7 +386,8 @@ export class OrgLibrary {private reconcile(applied: AppliedLibrary): void {this.rebuild();- this.handleWithdrawn();+ const releases = this.releases();+ if (releases) { handleWithdrawn(releases); applyUpdates(releases); }this.state.source = { adminOrigin: applied.adminOrigin, organizationId: applied.organizationId };this.state.appliedDigest = applied.digest;this.save();@@ -388,6 +395,16 @@ export class OrgLibrary {}+ private releases(): ReleaseContext | null {+ const library = this.library;+ if (!library) return null;+ return {+ installs: this.state.installs, entries: library.catalog.packages, currentInstallId: (packageId) => this.currentInstallId(packageId),+ releaseDocument: (entry) => { const read = this.releaseDocument(entry); return read.ok ? read.value : null; },+ installedDocument: (install) => this.installDocument(install), deps: this.deps, now: () => this.deps.now?.() ?? Date.now(),+ };+ }+private currentInstallId(packageId: string): string | null {return this.library ? orgInstallId(this.library.adminOrigin, this.library.organizationId, packageId) : null;}@@ -581,51 +598,6 @@ export class OrgLibrary {console.warn(`[org-library] removed a team that was only partly added when OpenMausBot stopped; it can be added again from the shelf`);}- private handleWithdrawn(): boolean {- if (!this.library) return false;- let changed = false;- for (const [installId, install] of Object.entries(this.state.installs)) {- if (this.currentInstallId(install.packageId) !== installId) continue;- if (install.status === "withdrawn" || (install.status === "removed" && install.withdrawnHandled === install.sha256)) continue;- const entry = this.library.catalog.packages.find((candidate) => candidate.packageId === install.packageId);- if (!entry?.withdrawnReleases.some((withdrawn) => withdrawn.sha256 === install.sha256)) continue;- this.switchOff(installId);- if (install.status === "installed") install.status = "withdrawn";- else install.withdrawnHandled = install.sha256;- install.updatedAt = this.deps.now?.() ?? Date.now();- changed = true;- }- return changed;- }-- private switchOff(installId: string): void {- for (const bot of this.deps.store.bots) {- for (const skill of this.deps.skills.stamps(bot.id)) {- if (skill.stamp.installId !== installId || !skill.enabled) continue;- const result = this.deps.skills.setEnabled(bot.id, skill.name, false);- if ("error" in result) console.warn(`[org-library] could not switch off ${skill.name}: ${result.error}`);- }- }- for (const bot of this.deps.store.bots) {- const made = bot.installedPackage;- if (made?.source !== "org" || made.installId !== installId || !made.presetKey || !made.ref) continue;- const source = `org:${made.ref}@${made.release}`;- for (const skill of this.deps.skills.list(bot.id)) {- if (skill.source !== source || !skill.enabled) continue;- const result = this.deps.skills.setEnabled(bot.id, skill.name, false);- if ("error" in result) console.warn(`[org-library] could not switch off ${skill.name}: ${result.error}`);- }- }- for (const routine of this.deps.routines.packageStamps()) {- if (routine.stamp.installId !== installId || !routine.enabled) continue;- try {- this.deps.routines.update(routine.routineId, { enabled: false });- } catch (error) {- console.warn(`[org-library] could not pause a routine: ${error instanceof Error ? error.message : String(error)}`);- }- }- }-private onStoreChange(change: StoreChange): void {if (change.type !== "bot.deleted" && change.type !== "group.deleted" && change.type !== "sections") return;if (!Object.keys(this.state.installs).length) return;diff --git a/src/lib/org-library.test.ts b/src/lib/org-library.test.tsindex 21fcad05f9..be1e7af06e 100644--- a/src/lib/org-library.test.ts+++ b/src/lib/org-library.test.ts@@ -56,11 +56,13 @@ describe("the shelf card", () => {expect(orgModeBadge(entry())).toBeNull();expect(orgModeBadge(entry({ mode: "required" }))).toBe("Recommended by Acme Partners");expect(orgCardNotes(entry({ installed: { installId: "b".repeat(32), release: "1.2.0", status: "installed" } }))).toEqual([- "Version 1.3.0 available. Updates arrive automatically in an upcoming MausBot update.",+ "Version 1.3.0 available. It comes over on its own once it's downloaded, and keeps your changes.",]);expect(orgCardNotes(entry({ release: null, installed: { installId: "b".repeat(32), release: "1.3.0", status: "withdrawn" } }))).toEqual(["Withdrawn by Acme Partners",]);+ // A withdrawn install isn't updated, so it isn't told a newer release is coming.+ expect(orgCardNotes(entry({ installed: { installId: "b".repeat(32), release: "1.2.0", status: "withdrawn" } }))).toEqual(["Withdrawn by Acme Partners"]);expect(orgContentsLine(entry().contents)).toBe("Bots: 3 · Skills: 3 · Preset bots: 1 · Group chats: 1 · Routines: 2 · Connections: 1");expect(orgContentsLine({ bots: 0, skills: 2, presets: 0, rooms: 0, routines: 0, connections: 0, botNames: [] })).toBe("Skills: 2");});diff --git a/src/lib/org-library.ts b/src/lib/org-library.tsindex 8b5b27b33c..dc73edd57a 100644--- a/src/lib/org-library.ts+++ b/src/lib/org-library.ts@@ -64,7 +64,7 @@ export function orgModeBadge(entry: Pick<OrgLibraryPackage, "mode" | "publisher"export function orgCardNotes(entry: OrgLibraryPackage): string[] {const notes: string[] = [];if (entry.installed?.status === "withdrawn") notes.push(t("orgLibrary.withdrawn", { name: entry.publisher.name }));- if (entry.installed && entry.installed.status !== "removed" && entry.release && entry.release.version !== entry.installed.release) {+ if (entry.installed?.status === "installed" && entry.release && entry.release.version !== entry.installed.release) {notes.push(t("orgLibrary.newerRelease", { version: entry.release.version }));}return notes;diff --git a/src/locales/en.json b/src/locales/en.jsonindex b5c9b371b1..e92a643fb9 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -1898,7 +1898,7 @@"orgLibrary.fromSelf": "Your organization","orgLibrary.recommended": "Recommended by {name}","orgLibrary.withdrawn": "Withdrawn by {name}",- "orgLibrary.newerRelease": "Version {version} available. Updates arrive automatically in an upcoming {app} update.",+ "orgLibrary.newerRelease": "Version {version} available. It comes over on its own once it's downloaded, and keeps your changes.","orgLibrary.bots": "Bots: {count}","orgLibrary.skills": "Skills: {count}","orgLibrary.presets": "Preset bots: {count}",diff --git a/src/locales/es.json b/src/locales/es.jsonindex 312451deba..aa3007af52 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -1541,7 +1541,6 @@"orgLibrary.fromSelf": "Tu organización","orgLibrary.recommended": "Recomendado por {name}","orgLibrary.withdrawn": "Retirado por {name}",- "orgLibrary.newerRelease": "Versión {version} disponible. Las actualizaciones llegan automáticamente con una próxima actualización de {app}.","orgLibrary.bots": "Bots: {count}","orgLibrary.skills": "Habilidades: {count}","orgLibrary.presets": "Preajustes de bot: {count}",diff --git a/src/locales/it.json b/src/locales/it.jsonindex 3192f02ce3..6eef48bd78 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -1667,7 +1667,6 @@"orgLibrary.fromSelf": "La tua organizzazione","orgLibrary.recommended": "Consigliato da {name}","orgLibrary.withdrawn": "Ritirato da {name}",- "orgLibrary.newerRelease": "Versione {version} disponibile. Gli aggiornamenti arrivano in automatico con un prossimo aggiornamento di {app}.","orgLibrary.bots": "Bot: {count}","orgLibrary.skills": "Abilità: {count}","orgLibrary.presets": "Bot preset: {count}",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 0e9bf7b0dc..a51c146fd6 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -1703,7 +1703,6 @@"orgLibrary.fromSelf": "あなたの組織","orgLibrary.recommended": "{name} のおすすめ","orgLibrary.withdrawn": "{name} が公開を取り下げました",- "orgLibrary.newerRelease": "バージョン {version} が利用可能です。今後の {app} の更新時に自動で更新されます。","orgLibrary.bots": "ボット: {count} 体","orgLibrary.skills": "スキル: {count} 件","orgLibrary.presets": "プリセットボット: {count} 件",diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex e6f4cadd85..f807037ba5 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -1786,7 +1786,6 @@"orgLibrary.fromSelf": "내 조직","orgLibrary.recommended": "{name} 추천","orgLibrary.withdrawn": "{name}이(가) 철회함",- "orgLibrary.newerRelease": "버전 {version} 출시. 다음 {app} 업데이트에서 자동으로 반영돼요.","orgLibrary.bots": "봇: {count}개","orgLibrary.skills": "스킬: {count}개","orgLibrary.presets": "프리셋 봇: {count}개",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex 5ebfec6702..8acdceec86 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -1696,7 +1696,6 @@"orgLibrary.fromSelf": "Twoja organizacja","orgLibrary.recommended": "Polecane przez {name}","orgLibrary.withdrawn": "Wycofane przez {name}",- "orgLibrary.newerRelease": "Dostępna wersja {version}. Aktualizacje pojawią się automatycznie w najbliższej aktualizacji {app}.","orgLibrary.bots": "Boty: {count}","orgLibrary.skills": "Umiejętności: {count}","orgLibrary.presets": "Boty z ustawień wstępnych: {count}",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 8fe32c2164..78a56dd373 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -1600,7 +1600,6 @@"orgLibrary.fromSelf": "Sua organização","orgLibrary.recommended": "Recomendado por {name}","orgLibrary.withdrawn": "Retirado por {name}",- "orgLibrary.newerRelease": "Versão {version} disponível. As atualizações chegam automaticamente em uma próxima atualização do {app}.","orgLibrary.bots": "Bots: {count}","orgLibrary.skills": "Habilidades: {count}","orgLibrary.presets": "Bots predefinidos: {count}",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex ee6cc7fa62..20992f1e13 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -1702,7 +1702,6 @@"orgLibrary.fromSelf": "Ваша организация","orgLibrary.recommended": "Рекомендовано {name}","orgLibrary.withdrawn": "Отозвано {name}",- "orgLibrary.newerRelease": "Доступна версия {version}. Обновления будут приходить автоматически в одном из ближайших обновлений {app}.","orgLibrary.bots": "Боты: {count}","orgLibrary.skills": "Навыки: {count}","orgLibrary.presets": "Пресеты ботов: {count}",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex 9868a6c55e..014e35f861 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -1250,7 +1250,6 @@"orgLibrary.fromSelf": "Organizasyonunuz","orgLibrary.recommended": "{name} tarafından önerildi","orgLibrary.withdrawn": "{name} tarafından geri çekildi",- "orgLibrary.newerRelease": "Sürüm {version} mevcut. Güncellemeler, gelecek bir {app} güncellemesinde otomatik olarak gelir.","orgLibrary.bots": "Botlar: {count}","orgLibrary.skills": "Beceriler: {count}","orgLibrary.presets": "Ön ayarlı botlar: {count}",diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex 475c50665f..a5dde251bb 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -1250,7 +1250,6 @@"orgLibrary.fromSelf": "Tổ chức của bạn","orgLibrary.recommended": "Được {name} đề xuất","orgLibrary.withdrawn": "Đã bị {name} thu hồi",- "orgLibrary.newerRelease": "Đã có phiên bản {version}. Nội dung cập nhật sẽ tự động áp dụng trong bản cập nhật {app} sắp tới.","orgLibrary.bots": "Bot: {count}","orgLibrary.skills": "Kỹ năng: {count}","orgLibrary.presets": "Bot preset: {count}",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 6128add6cb..9438c47b31 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -1085,7 +1085,6 @@"orgLibrary.fromSelf": "你的組織","orgLibrary.recommended": "{name} 推薦","orgLibrary.withdrawn": "{name} 已撤回",- "orgLibrary.newerRelease": "已有 {version} 版。更新會在即將推出的 {app} 更新中自動套用。","orgLibrary.bots": "機器人:{count}","orgLibrary.skills": "技能:{count}","orgLibrary.presets": "預設組態:{count}",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 51a6d7ce1e..96446b5363 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -1884,7 +1884,6 @@"orgLibrary.fromSelf": "你的组织","orgLibrary.recommended": "{name} 推荐","orgLibrary.withdrawn": "{name} 已撤回",- "orgLibrary.newerRelease": "已有 {version} 版。更新会随之后的 {app} 更新自动送达。","orgLibrary.bots": "机器人:{count}","orgLibrary.skills": "技能:{count}","orgLibrary.presets": "预设机器人:{count}",