diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f05d8a1..51e8c7e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,6 +25,19 @@ jobs: run: | npm exec --yes --package=@anthropic-ai/claude-code@2.1.291 -- claude plugin validate ./plugins/openorange --strict npm exec --yes --package=@anthropic-ai/claude-code@2.1.291 -- claude plugin validate . --strict + # The Buzz Desktop plugin against a stub ACP agent in place of `oo acp`: no Sunport, no network. + buzz-plugin: + name: Buzz plugin + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 + with: + node-version: '24.22.1' + - run: node --test --test-timeout=30000 tests/test_buzz_plugin.mjs # The guide names exactly the tools the hosted MCP lists publicly today, read with no credentials. A job of its own: # the hosted MCP changes on its own deploys, and its being down says nothing about the package. live-tools: diff --git a/README.md b/README.md index ff7b8a6..d0c7d22 100644 --- a/README.md +++ b/README.md @@ -191,9 +191,35 @@ the Sunport to keep the same agent. The sign-in stays on Cursor's servers, never on the Bot's computer. Grok Bot's computer can also run the `oo` CLI ([CLI guide](usage/references/cli.md)). +## Buzz Desktop + +The Buzz plugin is in [`packages/buzz/openorange-buzz`](packages/buzz/openorange-buzz). +It makes OpenOrange an agent type in Buzz Desktop: mention your agent in a +thread and it answers there from your Sunport, each thread one continuing +conversation. Buzz passes the messages to `oo` on your computer, which reaches +your Sunport as you. + +You need Buzz Desktop and, on the same computer, the `oo` CLI with `oo login` +done ([CLI guide](usage/references/cli.md)). + +1. Open this link on that computer, for example from your browser's address bar: + + ```text + buzz://plugin-install?repository=https%3A%2F%2Fgithub.com%2F2bb-dev%2Fopenorange-integrations.git&path=packages%2Fbuzz%2Fopenorange-buzz + ``` + + Or, in Buzz, open **Settings › Plugins › Manage plugins**, choose **Add**, and + enter the repository `2bb-dev/openorange-integrations` and the folder + `packages/buzz/openorange-buzz`. Buzz shows the access the plugin asks for, + starting `oo acp`; choose **Install plugin**. +2. Open **Agents › New agent › Custom › Harness › OpenOrange**. The agent is + Clem on your Sunport. +3. Mention the agent in a thread. It answers only your own mentions, while Buzz + Desktop is open. + ## The packages -All three packages use the same [MCP guide](usage/references/mcp.md) and +The Claude, OpenAI and Grok Bot packages use the same [MCP guide](usage/references/mcp.md) and [CLI guide](usage/references/cli.md), with the connection format required by each assistant. Additional assistants can reuse these usage guides. diff --git a/packages/buzz/openorange-buzz/README.md b/packages/buzz/openorange-buzz/README.md new file mode 100644 index 0000000..cbb91a2 --- /dev/null +++ b/packages/buzz/openorange-buzz/README.md @@ -0,0 +1,14 @@ +# OpenOrange + +Talk to your OpenOrange agents, such as Clem, in Buzz. Mention the agent in a +thread and it answers there from your Sunport; each thread is one continuing +conversation. + +## Getting started + +1. Install `oo`, OpenOrange's command line, from https://app.openorange.ai/connect + on this computer, and run `oo login` in a terminal. +2. In Buzz, open **Agents**, choose **New agent**, then **Custom**, **Harness** + and **OpenOrange**. +3. Mention the agent in a thread. It answers your own mentions while Buzz + Desktop is open. diff --git a/packages/buzz/openorange-buzz/manifest.json b/packages/buzz/openorange-buzz/manifest.json new file mode 100644 index 0000000..5bcb484 --- /dev/null +++ b/packages/buzz/openorange-buzz/manifest.json @@ -0,0 +1,17 @@ +{ + "id": "openorange.agents", + "name": "OpenOrange", + "apiVersion": 1, + "description": "Talk to your OpenOrange agents, such as Clem, in Buzz. They keep running on your Sunport; this computer only passes messages.", + "host": { + "processes": [ + { + "id": "oo", + "program": "oo", + "args": [ + "acp" + ] + } + ] + } +} diff --git a/packages/buzz/openorange-buzz/plugin.js b/packages/buzz/openorange-buzz/plugin.js new file mode 100644 index 0000000..725316f --- /dev/null +++ b/packages/buzz/openorange-buzz/plugin.js @@ -0,0 +1,313 @@ +// OpenOrange in Buzz: an agent type whose agents are the owner's agents on their Sunport, Clem unless the agent's +// config names another. Buzz keeps the agent's identity and posts its replies. Each thread the agent is mentioned in is +// one continuing conversation with the Sunport's agent, reached through `oo acp` (the Agent Client Protocol on stdin +// and stdout), which signs in as the person who ran `oo login`. Nothing of the agent runs on this computer, and no key +// of Buzz's ever reaches `oo`. +export const inject = ["agents", "host"]; + +const TYPE_ID = "agent"; +/** The Sunport agent a Buzz agent is, when its config names none. */ +const DEFAULT_AGENT = "clem"; +const SAVED = "openorange.agents.sessions.v1"; +const SAVED_LIMIT = 500; +export function apply(ctx) { + const { agents, host } = ctx; + // Only the desktop app can start `oo`. + if (!host.spawn) return; + const kit = agents.harness; + if (!kit) throw new Error("This Buzz cannot run agents a plugin brings yet. Update Buzz, then turn this plugin on again."); + const bridges = createBridges(host.spawn.bind(host)); + const saved = createSaved(globalThis.localStorage); + const turns = new Map(); + ctx.effect(() => () => bridges.stop()); + + agents.register({ + id: TYPE_ID, + title: "OpenOrange", + description: + "An agent of your OpenOrange Sunport, Clem by default, reached with oo on this computer. Each thread it is mentioned in is one continuing conversation.", + defaults: () => ({ config: { agent: DEFAULT_AGENT } }), + summary: (agent) => `${sunportAgent(agent.config)} on your Sunport`, + timeoutMs: 30 * 60_000, + run: (delivery) => { + // One turn at a time for an agent: its next mention waits for the one it is answering. + const key = delivery.agent.key; + const next = (turns.get(key) ?? Promise.resolve()).then(() => turn(delivery, kit, bridges, saved)); + const settled = next.catch(() => undefined); + turns.set(key, settled); + void settled.then(() => turns.get(key) === settled && turns.delete(key)); + return next; + }, + }); +} + +/** The Sunport agent a Buzz agent's config names: an id or alias `oo acp --agent` takes. */ +function sunportAgent(config) { + const named = typeof config?.agent === "string" ? config.agent.trim() : ""; + return /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(named) ? named : DEFAULT_AGENT; +} + +async function turn(delivery, kit, bridges, saved) { + const { agent, signal } = delivery; + const target = sunportAgent(delivery.config); + const conversation = await kit.conversation(delivery, "thread"); + if (!conversation) { + delivery.ignored?.(); + return; + } + if (!delivery.current()) return; + const key = `${agent.key}|${target}|${conversation.key}`; + let prompt; + try { + const acp = await bridges.connect(target); + let kept = saved.get(key); + if (kept && !acp.open.has(kept.session)) { + try { + await acp.request("session/resume", { sessionId: kept.session, cwd: "/", mcpServers: [] }); + acp.open.add(kept.session); + } catch { + kept = undefined; // archived or gone on the Sunport: start over, shown the conversation again + } + } + let session = kept?.session; + if (!session) { + // Where the conversation is, for the Sunport to show beside it. + const place = { _meta: { openorange: { place: conversation.where } } }; + session = (await acp.request("session/new", { cwd: "/", mcpServers: [], ...place })).sessionId; + acp.open.add(session); + } + prompt = await kit.turnPrompt(delivery, conversation, kept?.cursor ? { cursor: kept.cursor } : {}); + signal.throwIfAborted(); + if (!delivery.current()) { + prompt.restore(); + return; + } + let text = ""; + acp.updates.set(session, (update) => { + if (update.sessionUpdate === "agent_message_chunk" && update.content?.type === "text") text += update.content.text; + else if (update.sessionUpdate === "tool_call") delivery.step?.(String(update.title || update.kind || "tool")); + else if (update.sessionUpdate === "session_info_update" && update.title) delivery.named?.(String(update.title)); + }); + const stop = () => acp.notify("session/cancel", { sessionId: session }); + signal.addEventListener("abort", stop, { once: true }); + delivery.interruptible?.(stop); + delivery.acknowledged?.(); + let result; + try { + result = await acp.request("session/prompt", { + sessionId: session, + prompt: [{ type: "text", text: message(delivery, conversation, prompt.text, !kept) }], + }); + } finally { + signal.removeEventListener("abort", stop); + acp.updates.delete(session); + } + saved.set(key, { session, cursor: prompt.cursor }); + const reply = text.trim(); + if (reply) await kit.reply(agent, conversation, reply); + else if (result?.stopReason !== "cancelled") await kit.reply(agent, conversation, "I finished this turn without a reply."); + } catch (error) { + prompt?.restore(); + if (signal.aborted) throw error; + await kit + .reply(agent, conversation, `I could not answer: ${explain(error)}`, { notifyOwner: true }) + .catch(() => undefined); + throw error; + } +} + +/** What the agent is sent for a turn, and so what its conversation on the Sunport shows: the person's own words, then + * anything others wrote in the thread since the agent last saw it, and on a conversation's first turn where it is from. + * Buzz's own prompt is written for agents with Buzz's tools, so only its unseen messages are taken from it. */ +function message(delivery, conversation, prompt, first) { + const { trigger, agent } = delivery; + const event = trigger.type === "mention" ? trigger.event : undefined; + // A wake has no message of a person's: Buzz's text for it is all there is. + if (!event) return prompt; + const said = saidTo(event.content, agent.name) || "(mentioned you without a message)"; + const earlier = unseen(prompt, agent.pubkey, event.id); + return [ + said, + earlier.length ? `Earlier in this Buzz thread:\n${earlier.join("\n")}` : "", + first ? `(Sent from Buzz, ${conversation.where}. Your reply is posted there as your message.)` : "", + ] + .filter(Boolean) + .join("\n\n"); +} + +/** A mention's text without the agent's own name at its start. */ +function saidTo(content, name) { + let text = String(content ?? "").trim(); + const own = `@${name}`.toLowerCase(); + while (text.toLowerCase().startsWith(own)) text = text.slice(own.length).replace(/^[\s,:]+/, ""); + return text.trim(); +} + +/** The messages Buzz's prompt lists as not yet shown, as "name: text" lines, without the agent's own. */ +function unseen(prompt, own, current) { + const found = /<(thread-context|conversation-context)>\n([\s\S]*?)\n<\/\1>/.exec(prompt); + if (!found) return []; + try { + const messages = JSON.parse(found[2]).messages; + return (Array.isArray(messages) ? messages : []) + .filter((item) => item && item.pubkey !== own && item.id !== current && typeof item.content === "string" && item.content.trim()) + .map((item) => `${item.display_name || item.name || "Someone"}: ${item.content.trim()}`); + } catch { + return []; + } +} + +/** What to tell the owner when a turn fails. */ +function explain(error) { + const message = String(error?.message ?? error).trim(); + if (/os error 2|no such file|not found/i.test(message)) + return "the oo command was not found on this computer. Install it from your Sunport (Connect, then Command line), run `oo login`, and mention me again."; + if (/not signed in|login|credential|unauthori[sz]ed|\b401\b/i.test(message)) + return `oo is not signed in to your Sunport. Run \`oo login\` in a terminal, then mention me again. (${message.slice(0, 300)})`; + return message.slice(0, 600) || "oo stopped without saying why."; +} + +/** One `oo acp` for each Sunport agent in use. */ +function createBridges(spawn) { + const made = new Map(); + return { + connect(target) { + if (!made.has(target)) made.set(target, createBridge(spawn, target)); + return made.get(target).connect(); + }, + stop() { + for (const bridge of made.values()) bridge.stop(); + }, + }; +} + +/** One `oo acp` for every conversation with a Sunport agent, started when first needed and again after it exits. */ +function createBridge(spawn, target) { + let connection; + let starting; + let stopped = false; + + async function start() { + const pending = new Map(); + const updates = new Map(); + const open = new Set(); + let ids = 0; + let buffered = ""; + let errors = ""; + let ended; + let process; + const write = (message) => process.write(`${JSON.stringify(message)}\n`); + + const read = (line) => { + let message; + try { + message = JSON.parse(line); + } catch { + return; + } + if (message.id !== undefined && message.method === undefined) { + const waiting = pending.get(message.id); + pending.delete(message.id); + if (!waiting) return; + if (message.error) waiting.reject(new Error(message.error.message || "oo refused the request")); + else waiting.resolve(message.result); + } else if (message.method === "session/update") { + updates.get(message.params?.sessionId)?.(message.params.update ?? {}); + } else if (message.id !== undefined) { + // A request of oo's own, such as an approval: this plugin shows none, so the agent is told it was not given. + void write({ jsonrpc: "2.0", id: message.id, result: { outcome: { outcome: "cancelled" } } }).catch(() => undefined); + } + }; + + process = await spawn("oo", { + args: ["--agent", target], + onStdout: (data) => { + buffered += data; + for (let at = buffered.indexOf("\n"); at >= 0; at = buffered.indexOf("\n")) { + const line = buffered.slice(0, at).trim(); + buffered = buffered.slice(at + 1); + if (line) read(line); + } + }, + onStderr: (data) => { + errors = (errors + data).slice(-1200); + }, + }); + const request = (method, params) => + new Promise((resolve, reject) => { + if (ended) return reject(ended); + const id = ++ids; + pending.set(id, { resolve, reject }); + write({ jsonrpc: "2.0", id, method, params }).catch((error) => { + pending.delete(id); + reject(error); + }); + }); + const notify = (method, params) => write({ jsonrpc: "2.0", method, params }).catch(() => undefined); + const self = { request, notify, updates, open, kill: () => process.kill() }; + void Promise.resolve(process.exited) + .catch(() => undefined) + .then(() => { + ended = new Error(errors.trim().split("\n").pop() || "oo stopped"); + if (connection === starting) connection = undefined; + for (const waiting of pending.values()) waiting.reject(ended); + pending.clear(); + }); + await request("initialize", { + protocolVersion: 1, + clientCapabilities: {}, + clientInfo: { name: "buzz", title: "Buzz", version: "1" }, + }); + return self; + } + + return { + connect() { + if (stopped) return Promise.reject(new Error("The OpenOrange plugin was turned off")); + if (!connection) { + const mine = start(); + starting = mine; + connection = mine; + mine.catch(() => { + if (connection === mine) connection = undefined; + }); + } + return connection; + }, + stop() { + stopped = true; + const last = connection; + connection = undefined; + void last?.then((acp) => acp.kill()).catch(() => undefined); + }, + }; +} + +/** Each conversation's session on the Sunport and what it has been shown, kept on this computer. */ +function createSaved(storage) { + const load = () => { + try { + const value = JSON.parse(storage?.getItem(SAVED) ?? "{}"); + return value && typeof value === "object" ? value : {}; + } catch { + return {}; + } + }; + return { + get(key) { + const found = load()[key]; + return typeof found?.session === "string" ? found : undefined; + }, + set(key, value) { + const all = load(); + delete all[key]; + all[key] = value; + const kept = Object.fromEntries(Object.entries(all).slice(-SAVED_LIMIT)); + try { + storage?.setItem(SAVED, JSON.stringify(kept)); + } catch { + // Without storage, a restart starts each conversation over. + } + }, + }; +} diff --git a/scripts/package.py b/scripts/package.py index e101daf..dcc9c49 100644 --- a/scripts/package.py +++ b/scripts/package.py @@ -40,11 +40,18 @@ } # A host's own files from the repository's: the ChatGPT/Codex card logo, the ring on charcoal. HOST_FILES = {"openai": {"assets/openorange-logo-512.png": "assets/openorange-logo-512.png"}} +# Buzz Desktop installs this folder from the repository as it is, so nothing here generates or builds it: its manifest, +# one self-contained plugin.js and a README. Buzz refuses a manifest with any other key, updates an installed plugin by +# its id, and shows the person the computer access it asks for at install: starting `oo acp`, nothing else. +BUZZ = "packages/buzz/openorange-buzz" +BUZZ_FILES = ("manifest.json", "plugin.js", "README.md") +BUZZ_MANIFEST = {"id", "name", "apiVersion", "description", "discovery", "host"} +BUZZ_HOST = {"processes": [{"id": "oo", "program": "oo", "args": ["acp"]}]} SOURCE_FILES = { "README.md", "LICENSE", ".gitignore", ".claude-plugin/marketplace.json", ".cursor-plugin/marketplace.json", "assets/openorange.svg", "assets/openorange-icon-1024.png", "assets/openorange-logo-512.png", "usage/README.md", "usage/SKILL.md", "usage/references/mcp.md", "usage/references/cli.md", "usage/agent-guide.json", "scripts/package.py", "scripts/live_tools.py", "tests/test_package.py", - ".github/workflows/ci.yml", + "tests/test_buzz_plugin.mjs", "tests/acp_stub.mjs", ".github/workflows/ci.yml", } # How an agent stays in touch with its Sunport comes from one source in the Layer # (packages/billing/src/contracts/agent-guide.ts). Its guideJson() export is vendored @@ -180,6 +187,11 @@ def check(root): raise ValueError("Cursor marketplace must use the contained Grok Bot package") if cursor["metadata"]["version"] not in versions: raise ValueError("Cursor marketplace version differs") + buzz = json.loads(read_file(root, f"{BUZZ}/manifest.json")) + if (not set(buzz) <= BUZZ_MANIFEST or buzz.get("id") != "openorange.agents" or buzz.get("apiVersion") != 1 + or buzz.get("host") != BUZZ_HOST): + raise ValueError("Buzz plugin must keep its id, the manifest keys Buzz accepts and only oo acp") + expected.update(f"{BUZZ}/{name}" for name in BUZZ_FILES) actual = set() for path in root.rglob("*"): relative = path.relative_to(root) diff --git a/tests/acp_stub.mjs b/tests/acp_stub.mjs new file mode 100644 index 0000000..f381ce3 --- /dev/null +++ b/tests/acp_stub.mjs @@ -0,0 +1,60 @@ +// A stand-in for `oo acp` with no Sunport behind it: the Agent Client Protocol as `oo acp` speaks it, one JSON-RPC +// message per line on stdin and stdout. Its sessions and every message it receives are kept in the file named by +// ACP_STUB_STATE, so a test can read them and a stub started after a restart resumes the sessions an earlier one made. +// Each turn answers "Turn of ." in two chunks. A prompt asking to "count slowly" shows a tool call and runs +// until session/cancel. ACP_STUB_REFUSE='{"method": …, "message": …}' answers that method with a JSON-RPC error. +import { readFileSync, writeFileSync } from "node:fs"; +import { createInterface } from "node:readline"; + +const file = process.env.ACP_STUB_STATE; +const refuse = JSON.parse(process.env.ACP_STUB_REFUSE || "null"); +let state; +try { + state = JSON.parse(readFileSync(file, "utf8")); +} catch { + state = { starts: [], received: [], sessions: {}, made: 0 }; +} +const save = () => writeFileSync(file, JSON.stringify(state)); +state.starts.push(process.argv.slice(2)); +save(); + +const send = (message) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`); +const update = (sessionId, change) => send({ method: "session/update", params: { sessionId, update: change } }); +const text = (sessionId, words) => update(sessionId, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: words } }); +const unknown = (id) => send({ id, error: { code: -32602, message: "Session not found" } }); +/** The prompt of each session that runs until it is cancelled. */ +const running = new Map(); + +createInterface({ input: process.stdin }).on("line", (line) => { + const { id, method, params = {} } = JSON.parse(line); + state.received.push({ method, params }); + save(); + if (method === refuse?.method) return send({ id, error: { code: -32000, message: refuse.message } }); + if (method === "initialize") + return send({ id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true }, authMethods: [] } }); + if (method === "session/new") { + const sessionId = `session-${++state.made}`; + state.sessions[sessionId] = 0; + save(); + return send({ id, result: { sessionId } }); + } + if (method === "session/resume") return params.sessionId in state.sessions ? send({ id, result: {} }) : unknown(id); + if (method === "session/prompt") { + const { sessionId } = params; + if (!(sessionId in state.sessions)) return unknown(id); + const turn = ++state.sessions[sessionId]; + save(); + if (/count slowly/.test(params.prompt?.[0]?.text ?? "")) { + update(sessionId, { sessionUpdate: "tool_call", toolCallId: "count", title: "Counting", status: "in_progress" }); + return running.set(sessionId, id); + } + text(sessionId, `Turn ${turn} `); + text(sessionId, `of ${sessionId}.`); + return send({ id, result: { stopReason: "end_turn" } }); + } + if (method === "session/cancel") { + if (running.has(params.sessionId)) send({ id: running.get(params.sessionId), result: { stopReason: "cancelled" } }); + return running.delete(params.sessionId); + } + if (id !== undefined) send({ id, error: { code: -32601, message: `Method not found: ${method}` } }); +}); diff --git a/tests/test_buzz_plugin.mjs b/tests/test_buzz_plugin.mjs new file mode 100644 index 0000000..a520980 --- /dev/null +++ b/tests/test_buzz_plugin.mjs @@ -0,0 +1,283 @@ +// The Buzz Desktop plugin (packages/buzz/openorange-buzz) run outside Buzz, with no Sunport and no network: a stand-in +// for the plugin context Buzz gives it (agents.register, agents.harness, host.spawn, as Buzz's plugin docs give them) +// starts the stub ACP agent beside this file wherever the plugin starts `oo`. +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +const folder = new URL("../packages/buzz/openorange-buzz/", import.meta.url); +const manifest = JSON.parse(readFileSync(new URL("manifest.json", folder), "utf8")); +// Buzz loads plugin.js from a blob URL, where any import fails; a data URL holds it to one self-contained file alike. +const plugin = await import(`data:text/javascript;base64,${readFileSync(new URL("plugin.js", folder)).toString("base64")}`); +const STUB = fileURLToPath(new URL("acp_stub.mjs", import.meta.url)); +const OWNER = "owner-pubkey"; +const FIRST_TURN = "\n\n(Sent from Buzz, #general. Your reply is posted there as your message.)"; + +/** One Buzz profile on one computer: the plugin's storage, and the stub `oo` (or none) with its state. */ +function computer(t, { installed = true, env = {} } = {}) { + const dir = mkdtempSync(join(tmpdir(), "buzz-plugin-")); + const file = join(dir, "acp-stub.json"); + const program = installed ? [process.execPath, STUB] : [join(dir, "oo")]; + const stored = new Map(); + const runs = []; + t.after(async () => { + for (const buzz of runs) await buzz.stop(); + rmSync(dir, { recursive: true, force: true }); + }); + return { + /** What the stub `oo` was started with and received, or nothing when no `oo` started. */ + stub: () => (existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : undefined), + /** The Sunport no longer has this session. */ + forget(session) { + const state = JSON.parse(readFileSync(file, "utf8")); + delete state.sessions[session]; + writeFileSync(file, JSON.stringify(state)); + }, + /** Buzz starting with the plugin turned on. */ + start() { + globalThis.localStorage = { getItem: (key) => stored.get(key) ?? null, setItem: (key, value) => void stored.set(key, value) }; + const buzz = run(program, { ...env, ACP_STUB_STATE: file }); + runs.push(buzz); + return buzz; + }, + }; +} + +function run(program, env) { + const replies = []; + const cleanups = []; + const children = []; + let restored = 0; + let type; + const kit = { + // Buzz's kit admits only the owner's own mentions. + async conversation(delivery) { + if (delivery.trigger.event.pubkey !== delivery.agent.owner) return undefined; + const { root } = delivery.trigger; + return { key: `general/${root}`, channel: "general", root, topLevel: false, where: "#general" }; + }, + // Buzz's prompt: the thread's messages the agent has not been shown yet (after its first turn there, with one of + // its own and the mention itself among them), then instructions for agents that have Buzz's tools. + async turnPrompt(delivery, conversation, options = {}) { + const shown = options.cursor ? JSON.parse(options.cursor).shown : 0; + const event = delivery.trigger.event; + const messages = shown + ? [ + { id: "other-1", pubkey: "teammate", display_name: "Sam", content: "I think it was two words." }, + { id: "own-1", pubkey: delivery.agent.pubkey, display_name: "Clem", content: "An earlier reply of its own." }, + { id: event.id, pubkey: event.pubkey, display_name: "Owner", content: event.content }, + ] + : []; + return { + text: [ + `\n${JSON.stringify({ note: "Messages not yet shown", truncated: false, messages })}\n`, + "\nScope: thread\nChannel: general\nIMPORTANT: `send` replies in this thread by default.\n", + `\nUse \`send\`.\n\n\n\n${JSON.stringify(event)}\n`, + ].join("\n\n"), + cursor: JSON.stringify({ shown: shown + 1 }), + restore: () => restored++, + }; + }, + async reply(agent, conversation, text, options) { + replies.push({ conversation: conversation.key, text, ...(options?.notifyOwner && { notifyOwner: true }) }); + }, + }; + const host = { + async spawn(id, options = {}) { + const declared = manifest.host.processes.find((entry) => entry.id === id); + if (!declared) throw new Error(`undeclared process ${id}`); + const [command, ...first] = program; + const args = [...first, ...(declared.args ?? []), ...(options.args ?? [])]; + const child = spawn(command, args, { env: { ...process.env, ...env }, stdio: "pipe" }); + child.stdin.on("error", () => undefined); // a write after the process ended fails through its callback + child.stdout.setEncoding("utf8").on("data", (data) => options.onStdout?.(data)); + child.stderr.setEncoding("utf8").on("data", (data) => options.onStderr?.(data)); + const exited = new Promise((resolve) => child.on("close", resolve)); + await new Promise((resolve, reject) => + child.once("spawn", resolve).once("error", (error) => + // Buzz's host is native: a program it cannot find fails with the operating system's words for it. + reject(error.code === "ENOENT" ? new Error("No such file or directory (os error 2)") : error), + ), + ); + children.push({ child, exited }); + return { + write: (data) => new Promise((resolve, reject) => child.stdin.write(data, (error) => (error ? reject(error) : resolve()))), + end: async () => void child.stdin.end(), + kill: async () => void child.kill("SIGTERM"), + exited, + }; + }, + }; + plugin.apply({ + agents: { harness: kit, register: (registered) => (type = registered) }, + host, + effect: (start) => cleanups.push(start()), + }); + let stopped; + return { + type, + replies, + restored: () => restored, + /** The plugin turned off: its cleanup runs, then Buzz ends the processes it started. */ + stop: () => + (stopped ??= (async () => { + for (const cleanup of cleanups) cleanup?.(); + for (const { child } of children) child.kill("SIGTERM"); + await Promise.all(children.map(({ exited }) => exited)); + })()), + }; +} + +let events = 0; +/** A mention of the agent in a thread, as Buzz delivers it to the agent type's `run`. */ +function mention(content, root, { author = OWNER } = {}) { + let started; + const seen = { steps: [], ignored: false, acknowledged: false, stop: undefined, started: new Promise((resolve) => (started = resolve)) }; + return { + seen, + delivery: { + trigger: { type: "mention", event: { id: `event-${++events}`, pubkey: author, content, created_at: events }, root }, + agent: { key: "agent-key", pubkey: "agent-pubkey", owner: OWNER, name: "Clem" }, + config: { agent: "clem" }, + signal: new AbortController().signal, + current: () => true, + step: (title) => (seen.steps.push(title), started()), + ignored: () => (seen.ignored = true), + acknowledged: () => (seen.acknowledged = true), + interruptible: (stop) => (seen.stop = stop), + }, + }; +} + +const prompts = (stub) => stub.received.filter((message) => message.method === "session/prompt").map((message) => message.params.prompt); + +test("registers OpenOrange as an agent type, Clem by default", (t) => { + const { type } = computer(t).start(); + assert.equal(type.id, "agent"); + assert.equal(type.title, "OpenOrange"); + assert.deepEqual(type.defaults(), { config: { agent: "clem" } }); + assert.equal(type.summary({ config: {} }), "clem on your Sunport"); +}); + +test("the owner's mention reaches `oo acp --agent clem` as the person's own words, and its reply is posted", async (t) => { + const here = computer(t); + const buzz = here.start(); + const first = mention("@Clem what is on my calendar today?", "root-1"); + await buzz.type.run(first.delivery); + assert.deepEqual(buzz.replies, [{ conversation: "general/root-1", text: "Turn 1 of session-1." }]); + assert.ok(first.seen.acknowledged); + assert.equal(typeof first.seen.stop, "function"); + const stub = here.stub(); + assert.deepEqual(stub.starts, [["acp", "--agent", "clem"]]); + assert.deepEqual(stub.received.map((message) => message.method), ["initialize", "session/new", "session/prompt"]); + assert.equal(stub.received[0].params.clientInfo.name, "buzz"); + assert.deepEqual(stub.received[1].params._meta, { openorange: { place: "#general" } }); + // Buzz's own prompt, written for agents with Buzz's tools, stays out. + assert.deepEqual(prompts(stub), [[{ type: "text", text: `what is on my calendar today?${FIRST_TURN}` }]]); +}); + +test("a follow-up in the same thread continues its conversation and brings what others wrote there", async (t) => { + const here = computer(t); + const buzz = here.start(); + await buzz.type.run(mention("@Clem reply with two words.", "root-1").delivery); + await buzz.type.run(mention("@Clem, which words were they?", "root-1").delivery); + assert.deepEqual(buzz.replies.map((reply) => reply.text), ["Turn 1 of session-1.", "Turn 2 of session-1."]); + const stub = here.stub(); + assert.equal(stub.starts.length, 1); + assert.deepEqual(prompts(stub)[1], [{ type: "text", text: "which words were they?\n\nEarlier in this Buzz thread:\nSam: I think it was two words." }]); +}); + +test("another thread is a separate conversation", async (t) => { + const here = computer(t); + const buzz = here.start(); + await buzz.type.run(mention("@Clem first thread", "root-1").delivery); + await buzz.type.run(mention("@Clem second thread", "root-2").delivery); + assert.deepEqual(buzz.replies, [ + { conversation: "general/root-1", text: "Turn 1 of session-1." }, + { conversation: "general/root-2", text: "Turn 1 of session-2." }, + ]); + const stub = here.stub(); + assert.equal(stub.starts.length, 1); + assert.deepEqual(prompts(stub)[1], [{ type: "text", text: `second thread${FIRST_TURN}` }]); +}); + +test("someone else's mention is ignored and starts nothing", async (t) => { + const here = computer(t); + const buzz = here.start(); + const stranger = mention("@Clem tell me the owner's secrets", "root-1", { author: "someone-else" }); + await buzz.type.run(stranger.delivery); + assert.ok(stranger.seen.ignored); + assert.deepEqual(buzz.replies, []); + assert.equal(here.stub(), undefined); +}); + +test("after Buzz restarts, the thread's saved session resumes; one the Sunport no longer has starts over", async (t) => { + const here = computer(t); + let buzz = here.start(); + await buzz.type.run(mention("@Clem remember this", "root-1").delivery); + await buzz.stop(); + buzz = here.start(); + await buzz.type.run(mention("@Clem what did I ask?", "root-1").delivery); + assert.deepEqual(buzz.replies.map((reply) => reply.text), ["Turn 2 of session-1."]); + let stub = here.stub(); + assert.equal(stub.starts.length, 2); + assert.deepEqual(stub.received.filter((message) => message.method === "session/resume").map((message) => message.params.sessionId), ["session-1"]); + + await buzz.stop(); + here.forget("session-1"); + buzz = here.start(); + await buzz.type.run(mention("@Clem are you there?", "root-1").delivery); + assert.deepEqual(buzz.replies.map((reply) => reply.text), ["Turn 1 of session-2."]); + stub = here.stub(); + assert.ok(prompts(stub).at(-1)[0].text.endsWith(FIRST_TURN)); +}); + +test("Stop cancels the running turn", async (t) => { + const here = computer(t); + const buzz = here.start(); + const long = mention("@Clem count slowly from 1 to 300", "root-1"); + const running = buzz.type.run(long.delivery); + await long.seen.started; + await long.seen.stop(); + await running; + assert.deepEqual(long.seen.steps, ["Counting"]); + assert.deepEqual(buzz.replies, []); + assert.deepEqual(here.stub().received.at(-1), { method: "session/cancel", params: { sessionId: "session-1" } }); +}); + +test("without oo on the computer, the owner is told to install it", async (t) => { + const buzz = computer(t, { installed: false }).start(); + await assert.rejects(buzz.type.run(mention("@Clem hello", "root-1").delivery), /os error 2/); + assert.deepEqual(buzz.replies, [ + { + conversation: "general/root-1", + text: "I could not answer: the oo command was not found on this computer. Install it from your Sunport (Connect, then Command line), run `oo login`, and mention me again.", + notifyOwner: true, + }, + ]); +}); + +test("a JSON-RPC error from the agent reaches the owner, and the thread's messages are shown again next turn", async (t) => { + const refused = { method: "session/prompt", message: "Clem is not available right now" }; + const buzz = computer(t, { env: { ACP_STUB_REFUSE: JSON.stringify(refused) } }).start(); + await assert.rejects(buzz.type.run(mention("@Clem hello", "root-1").delivery), { message: refused.message }); + assert.deepEqual(buzz.replies, [{ conversation: "general/root-1", text: `I could not answer: ${refused.message}`, notifyOwner: true }]); + assert.equal(buzz.restored(), 1); +}); + +test("when oo is not signed in, the owner is told to run `oo login`", async (t) => { + const refused = { method: "initialize", message: "Not signed in to a Sunport (401)" }; + const buzz = computer(t, { env: { ACP_STUB_REFUSE: JSON.stringify(refused) } }).start(); + await assert.rejects(buzz.type.run(mention("@Clem hello", "root-1").delivery)); + assert.deepEqual(buzz.replies, [ + { + conversation: "general/root-1", + text: `I could not answer: oo is not signed in to your Sunport. Run \`oo login\` in a terminal, then mention me again. (${refused.message})`, + notifyOwner: true, + }, + ]); +}); diff --git a/tests/test_package.py b/tests/test_package.py index f761658..0ac576d 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -230,6 +230,25 @@ def test_grok_bot_plugin_stays_in_its_apps_and_adds_nothing(self): package.check(self.root) path.write_bytes(original) + def test_buzz_plugin_keeps_its_id_and_asks_only_to_start_oo_acp(self): + path = self.root / package.BUZZ / "manifest.json" + original = path.read_bytes() + changes = { + "a key Buzz refuses": lambda manifest: manifest.update(version="0.6.36"), + "another id": lambda manifest: manifest.update(id="openorange.buzz"), + "a command": lambda manifest: manifest["host"].update(commands=[{"id": "status", "program": "git", "args": ["status"]}]), + "a network origin": lambda manifest: manifest["host"].update(networkOrigins=["https://example.com"]), + "another program": lambda manifest: manifest["host"]["processes"][0].update(program="sh"), + } + for label, change in changes.items(): + with self.subTest(change=label): + manifest = json.loads(original) + change(manifest) + path.write_text(json.dumps(manifest)) + with self.assertRaisesRegex(ValueError, "Buzz plugin"): + package.check(self.root) + path.write_bytes(original) + def test_marketplace_versions_follow_the_packages(self): changes = {".claude-plugin/marketplace.json": (lambda config: config["metadata"].update(version="9.9.9"), lambda config: config["plugins"][0].update(version="9.9.9")),