Skip to content

Commit 848924d

Browse files
feat(plugins): let a plugin wake an agent at a channel's top level (#3299)
## Why A plugin can only wake an agent inside an existing thread or a Solo chat, so it cannot have an agent start a new thread in a channel. ## What - Add optional `topLevel: true` to `ctx.agents.wake`. The wake lands at the channel's top level, the same conversation a whole-channel watch already uses. - Reject a wake that sets both `topLevel` and `root`. - Document the option in the plugin contract, the authoring guide and the agents guide. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent a25d661 commit 848924d

5 files changed

Lines changed: 35 additions & 7 deletions

File tree

‎docs/agents.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -534,9 +534,10 @@ one-off process; Codex: an ephemeral thread). Its signal aborts
534534
`STANDALONE_DEADLINE_MS` after it starts, including any wait for the harness to
535535
be ready. The prompt text lives in `attention-prompt.ts`.
536536

537-
A plugin wakes an agent with `ctx.agents.wake(pubkey, { channel, root?, text })`,
537+
A plugin wakes an agent with `ctx.agents.wake(pubkey, { channel, root?, topLevel?, text })`,
538538
in the conversation of that channel and thread, or of a Solo chat when it leaves
539-
out `root`. It throws when this copy of the app does not run the agent or its
539+
out `root`. `topLevel: true` wakes it at the top level of any other channel, the
540+
conversation a whole-channel watch wakes it in, so it can start a thread there. It throws when this copy of the app does not run the agent or its
540541
mention lane is full. The wake is a `plugin` trigger in the mention lane, with
541542
the mention's rate limit, and is dropped like a queued mention when the agent
542543
stops running here. Nothing goes to the relay. Claude, Codex, goose and Pi take

‎docs/plugin-architecture.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1046,10 +1046,11 @@ plugin's folder can replace that plugin's code, though not its host access,
10461046
without a new review. Plugin code is trusted and unsandboxed, so only load folders
10471047
that the agents you run may change.
10481048

1049-
`ctx.agents.wake(pubkey, { channel, root?, text })` wakes an agent this copy of
1049+
`ctx.agents.wake(pubkey, { channel, root?, topLevel?, text })` wakes an agent this copy of
10501050
the app runs in one of its conversations, as a mention there would, with no
10511051
message. `root` is the thread's root event id (64 hex); leave it out for a Solo
1052-
chat. The agent is told
1052+
chat. `topLevel: true`, without `root`, wakes it at the top level of a channel
1053+
that is not a Solo chat, for example to start a new thread there. The agent is told
10531054
the text comes from the plugin, not its owner, and is data, so quote what others
10541055
wrote (comments, check output) rather than phrasing it as instructions. It
10551056
throws when this copy does not run the agent or its queue is full. Claude, Codex and Goose accept plugin wakes; Pi ignores them. Attention delivery uses a separate internal `attention` trigger in the Interest lane, accepted by all four harnesses. Its Interest instructions retain their instruction framing, while observed messages remain data. A channel-only Attention address supplies a default posting destination and allows explicit thread replies outside Solo chats.

‎docs/plugin-authoring-guide.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ export function apply(ctx) {
6262
| `settingsCards` | A Settings destination | `ctx.settingsCards.register({ id, title, component, group?, personal?, identityRow? })`. `component` receives `{ active(), community?, navigation? }`; `navigation.target.route` can carry bounded, versioned presentation data for the card. Opening a route must never submit an operation. Optional `identityRow` receives `{ active() }` and contributes a compact account-status link inside Identity. Reuse the plugin’s existing session; check `active()` before navigation or an action. The row retires with its owning registration. Omit `icon` (it is a host icon component). The host supplies navigation and the content column, not a heading. |
6363
| `sidebarSections` (optional) | A section in the Team sidebar | `ctx.reflect.get("sidebarSections")?.register({ version: 1, id, title, icon, rows: { snapshot, subscribe }, select, actions? })`. `snapshot()` returns a stable array of `{ id, label, icon?, badge?, count?, status? }` until data changes, then notify subscribers. `select(row)` returns an open target such as `{ version: 1, kind: "home" }`. Actions: `{ id, label, icon: ReactElement, onSelect }`. |
6464
| `conversation` | Composer/message UI | `registerAccessory({ id, title, component, order?, placement? })` (read-only UI above the composer; props `{ session, scope, channelId, threadRootId?, canOpen, open }`; `placement`: `"composer"`, `"message"`, `"response"`). `registerMessage({ id, title, matches(message), component })`, `registerMessageAction({ id, title, matches(message, session), component })`, `registerIdentityMark({ id, title, component })` (presentation after a person's name in @mention suggestions; props `{ pubkey, profiles }`, where `profiles.snapshot().get(pubkey)?.verified` carries community verification), `registerLink({ id, title, matches(url), component })`, `registerLinkPreview({ id, title, matches(url), order?, component })` (a card below the message for one of its HTTPS links; props `{ url, messageId, open }`; lowest `order` wins, so claim your URLs below the default web card's `100`), `registerTool({ id, title, component })`. |
65-
| `agents` | Tools and hooks for agents | `ctx.agents.addTool({ name, description, inputSchema, call })`. `name` matches `/^[a-z][a-z0-9_]{0,63}$/`, is unique across plugins and not a Buzz tool name (prefix it with your plugin: `notes_get`). `inputSchema` is a JSON-serializable object with `type: "object"`. `async call(client, context, args)` resolves to a string (or `{ data, type, text? }`) and runs as the agent; a throw is shown to the agent as a tool error. Changing a tool's name, description or schema restarts some agent sessions, so edit deliberately. `ctx.agents.addInstructions({ id, text, when? })` gives every turn of the agents this copy runs, or those `when(agent)` accepts, a `<plugin-instructions>` section with `text` (at most 4096 UTF-8 bytes after trimming); it is sent with every turn, so keep it short. `ctx.agents.registerHook({ id, harness, event, run })` needs `host.agentHooks`. `ctx.agents.wake(agentKey, { channel, root?, text })` wakes a local agent (`root` is a 64-hex event id). With `host.files`, `ctx.agents.assignConversationFolder(agentKey, { channelId, root? }, path)` gives one conversation of a local Claude or Codex agent its own working folder before its first turn; see [Agents](agents.md). |
65+
| `agents` | Tools and hooks for agents | `ctx.agents.addTool({ name, description, inputSchema, call })`. `name` matches `/^[a-z][a-z0-9_]{0,63}$/`, is unique across plugins and not a Buzz tool name (prefix it with your plugin: `notes_get`). `inputSchema` is a JSON-serializable object with `type: "object"`. `async call(client, context, args)` resolves to a string (or `{ data, type, text? }`) and runs as the agent; a throw is shown to the agent as a tool error. Changing a tool's name, description or schema restarts some agent sessions, so edit deliberately. `ctx.agents.addInstructions({ id, text, when? })` gives every turn of the agents this copy runs, or those `when(agent)` accepts, a `<plugin-instructions>` section with `text` (at most 4096 UTF-8 bytes after trimming); it is sent with every turn, so keep it short. `ctx.agents.registerHook({ id, harness, event, run })` needs `host.agentHooks`. `ctx.agents.wake(agentKey, { channel, root?, topLevel?, text })` wakes a local agent (`root` is a 64-hex event id; `topLevel: true` instead wakes it at a channel's top level). With `host.files`, `ctx.agents.assignConversationFolder(agentKey, { channelId, root? }, path)` gives one conversation of a local Claude or Codex agent its own working folder before its first turn; see [Agents](agents.md). |
6666
| `shortcuts` | In-app key bindings | `ctx.shortcuts.register({ id, title, binding, run, when?, order?, allowInEditable?, allowInModal?, repeat? })`. `binding` is `{ key, mod?, shift?, alt?, ctrl? }` or an array; `mod` is Command on macOS, Control elsewhere. `key` is the logical key, case-insensitive (Space is `" "`). Skipped in text fields and modals unless opted in. |
6767
| `navigation` | Open destinations | `await ctx.navigation.open(target)` returns `{ status: "opened" \| "failed" \| "superseded" \| "cancelled" }`. Targets: `{ version: 1, kind: "plugin", pluginId, pageId?, params? }`, `{ version: 1, kind: "home" }`, `{ version: 1, kind: "settings", section? }`. |
6868
| `communityJoin` (optional) | Join a community the person chose in your UI | `ctx.reflect.get("communityJoin")?.open(address)` with a `wss://` or `https://` community address, for example one your plugin just created. It opens the app's join dialog, which connects at once; the person still completes admission and the profile step there, and nothing is saved before they do. An address already saved just selects that community. It returns `false` when the address is not a community origin (for example it has a path or credentials) or no identity is ready to join with (hand the address off another way), otherwise `true`; it reports no completion. Call it only from a live, user-initiated action. |

‎src/features/agents/service.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1959,6 +1959,23 @@ describe("a plugin's wake", () => {
19591959
}
19601960
});
19611961

1962+
it("wakes at a channel's top level when asked", async () => {
1963+
const { service, run, plugin, native } = await setup();
1964+
await service.create({ type: "example/echo", name: "Echo" });
1965+
await held(native);
1966+
plugin.agents.wake(bot, { channel, topLevel: true, text: "New work" });
1967+
await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1));
1968+
const { trigger } = run.mock.calls[0]?.[0] ?? {};
1969+
expect(trigger).toMatchObject({
1970+
type: "plugin",
1971+
plugin: "example",
1972+
channel,
1973+
topLevel: true,
1974+
text: "New work",
1975+
});
1976+
expect(trigger && "root" in trigger).toBe(false);
1977+
});
1978+
19621979
it("never publishes its own id, even when its turn fails", async () => {
19631980
vi.useFakeTimers({ shouldAdvanceTime: true });
19641981
const { service, run, plugin, native } = await setup();
@@ -2007,6 +2024,9 @@ describe("a plugin's wake", () => {
20072024
expect(() =>
20082025
plugin.agents.wake(bot, { channel, root: bad, text: "hi" }),
20092026
).toThrow(/64-hex event id/);
2027+
expect(() =>
2028+
plugin.agents.wake(bot, { channel, root, topLevel: true, text: "hi" }),
2029+
).toThrow(/not both/);
20102030
expect(() => plugin.agents.wake(sibling, { channel, text: "hi" })).toThrow(
20112031
/does not run that agent/,
20122032
);

‎src/features/agents/service.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -474,10 +474,13 @@ export type SessionUsage = Readonly<{
474474
observations: readonly UsageObservation[];
475475
}>;
476476
/** A conversation to wake an agent in, and what to tell it there. `root` is
477-
* the thread's root event id; leave it out for a Solo chat. */
477+
* the thread's root event id; leave it out for a Solo chat. `topLevel` wakes
478+
* it at the top level of a channel that is not a Solo chat, as a watch on the
479+
* whole channel does; without it, such a wake has no conversation. */
478480
export type AgentWake = Readonly<{
479481
channel: string;
480482
root?: string;
483+
topLevel?: true;
481484
text: string;
482485
}>;
483486
/** The conversation a self-handoff came from: no channel for a watch's or
@@ -3423,7 +3426,7 @@ export class AgentsService extends Service implements Agents {
34233426
}
34243427
private wakeIn(
34253428
key: AgentKey,
3426-
{ channel, root, text }: AgentWake,
3429+
{ channel, root, topLevel, text }: AgentWake,
34273430
source: Readonly<{ plugin: string } | { from: HandoffSource }>,
34283431
) {
34293432
if (!channel || !text.trim())
@@ -3432,11 +3435,14 @@ export class AgentsService extends Service implements Agents {
34323435
// them answering at the wake's own id.
34333436
if (root !== undefined && !/^[0-9a-f]{64}$/i.test(root))
34343437
throw new Error("A wake's root must be the thread's 64-hex event id");
3438+
if (topLevel !== undefined && (topLevel !== true || root !== undefined))
3439+
throw new Error("A wake is in a thread or at the top level, not both");
34353440
this.runners.wakeIn(key, {
34363441
type: "plugin",
34373442
...source,
34383443
channel,
34393444
...(root ? { root: root.toLowerCase() } : {}),
3445+
...(topLevel ? { topLevel } : {}),
34403446
text,
34413447
id: bytesToHex(crypto.getRandomValues(new Uint8Array(32))),
34423448
at: Date.now(),

0 commit comments

Comments
 (0)