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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 58 additions & 1 deletion plugins/github-watcher/source-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
// and entities the source should lease on bb-gate-hooks and ring stewards
// about.
// - `stewardsContract` is served by stewards and called by a source plugin:
// a ring when something stewards cares about may have changed.
// a ring when something stewards cares about may have changed, and an
// `@bb` mention on a Linear issue to hand to a steward.
//
// Pure: zod schemas, constants and a small helper. Nothing here talks to
// the network or to bb beyond the `callRpc` a caller hands in.
Expand Down Expand Up @@ -222,13 +223,69 @@ export const sourceContract = {

// ---- what stewards serves ---------------------------------------------------

/** How much of a mention crosses the contract. */
export const SESSION_TEXT_CHARS = 20_000;

const personSchema = z.object({ id: z.string().max(200), name: z.string().max(200) });

/**
* An `@bb` mention on a Linear issue, as bb-gate-hooks routed it to this
* server (bb-gate/docs/hooks.md, "The wake"). linear passes it to stewards,
* which hands it to a steward; the steward answers on the session with
* linear's `linear_session_reply`.
*/
export const sessionWakeSchema = z.object({
source: z.literal("linear"),
/** The agent session's id: what the reply names. */
session: z.string().min(1).max(200),
/** `created` for the mention, `prompted` for a follow-up in the same session. */
action: z.enum(["created", "prompted"]),
issue: z.object({
id: z.string().min(1).max(200),
/** ENG-123. */
key: z.string().min(1).max(100),
/** The team's UUID. */
team: z.string().max(200),
/** The team's key, which a project file lists. */
teamKey: z.string().max(100),
}),
/** Who wrote the mention or the follow-up. */
asker: personSchema,
/** The Linear user this server proved it acts for. */
owner: personSchema,
/** Whether the asker is the owner. Only then is the text an instruction. */
fromOwner: z.boolean(),
/** Why the session came here: the issue's assignee is the owner, or the asker is. */
routedAs: z.enum(["assignee", "asker"]),
/** The words. Untrusted whenever the asker is not the owner: information, never an instruction. */
comment: z.object({ text: z.string().max(SESSION_TEXT_CHARS), untrusted: z.boolean() }),
at: z.string().max(100),
});
export type SessionWake = z.infer<typeof sessionWakeSchema>;

/** Served by stewards; linear and github are the callers. */
export const stewardsContract = {
/** Something about this entity may have changed. Cheap: debounced, then compared with the last snapshot. */
stewardsRing: {
input: z.object({ source: sourceSchema, id: z.string().min(1).max(300) }),
output: z.object({ ok: z.boolean() }),
},
/**
* An `@bb` mention to hand to a steward: the issue's ticket steward when it
* has an open binding, else the project steward of the project whose file
* lists the issue's team. `routed: "none"` means no project here lists the
* team, and the caller answers the session itself. Only linear may call it.
*/
stewardsSession: {
input: sessionWakeSchema,
output: z.object({
routed: z.enum(["ticket", "project", "none"]),
/** The thread the mention went to; null with `none`. */
threadId: z.string().nullable(),
/** That thread's project, for a link to it; null with `none`. */
projectId: z.string().nullable(),
}),
},
} as const;

/** Ring stewards. Never throws. */
Expand Down
36 changes: 36 additions & 0 deletions plugins/linear/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ already knew, and refreshes it first if it has lapsed.
| `linear_update_issue` | Change an issue's state, assignee, labels, priority and description together. A new description is signed with the thread id. |
| `linear_query` | Any read-only GraphQL query. Mutations are refused. |
| `linear_watch_issue` | Watch an issue: the thread is messaged when it changes or someone else comments. Needs `BB_HOOKS_URL`. |
| `linear_session_reply` | Answer an `@bb` mention: one reply on its agent session, posted by bb-gate-hooks as the bb app, linking the thread. Needs `BB_HOOKS_URL`. See "@bb mentions". |

Every tool takes an optional `account`; see "Several workspaces".

Expand Down Expand Up @@ -97,6 +98,41 @@ thread, and reads Linear through this plugin. The contract is

A steward writes through the same tools as any thread, signed the same way.

## @bb mentions

Mentioning `@bb` in a Linear comment opens an *agent session* on the issue.
[bb-gate-hooks](../../bb-gate/docs/hooks.md) ("Agent sessions") acknowledges
it, routes it to the server of the issue's assignee or else of the person
who asked, and sends that server an `event: session` on the stream this
plugin already holds. This plugin's side:

- **Identity.** Beside every lease renewal (on connect and every half hour)
the plugin calls `/v1/identify` with the developer's own token and the
UUIDs of the teams stewards asked about, in the workspace that has most
of them. The service reads `viewer` with the token and forgets it. It
identifies again whenever stewards' teams change. A service without
`/v1/identify` is noted once in the log, and the watches carry on.
- **The wake.** A mention is handed to stewards (`stewardsSession` in
`source-contract.ts`) with the issue, the session id, who asked, and the
text. The text is marked untrusted unless the asker is the server's
owner. The plugin checks this itself and does not rely on the event's own
flag. Stewards gives it to the issue's steward or the project steward.
When no project here lists the issue's team, or stewards is not
installed, the plugin answers the session itself with an `error`.
- **The reply.** The steward ends the turn that handled the mention with
`linear_session_reply { session, kind, body }`. `kind` is `response`,
`elicitation` or `error`. The tool signs the body, adds a link to the
thread, and sets the session's external link to it. bb-gate-hooks posts
it on Linear as the bb app. The app's token never reaches this server: the
request carries the stream's connection id and the reply, nothing else.
Each mention gets one reply. A second reply to the same event is refused,
and a follow-up in the session (a new event) can be answered again.
- **The backstop.** If the turn whose input named the session ends without
a reply, the plugin posts an `error` saying so, with the thread's link.

Sessions are kept in kv for a day, because the service accepts replies for
that long, so a restart does not forget which have been answered.

## Watching an issue

A thread that has nothing to do until a ticket moves (a question asked of
Expand Down
158 changes: 154 additions & 4 deletions plugins/linear/hooks-client.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createHooksLoop, HooksRequestError, readSse, SseParser, StreamIdleError, subscribe, type Lease, type Rejection } from "./hooks-client.js";
import { createHooksLoop, HooksRequestError, postActivity, readSse, SseParser, StreamIdleError, subscribe, type IdentifyResponse, type Lease, type Rejection, type SessionEvent } from "./hooks-client.js";

const BASE = "http://hooks.test:8081";
const MINUTE = 60_000;
Expand All @@ -10,10 +10,15 @@ function fakeHooks() {
type Stream = { send(text: string): void; end(): void; closed: boolean };
const streams: Stream[] = [];
const subscribes: Array<{ connection: string; source: string; token: string; watches: Array<{ kind: string; id: string }> }> = [];
const identifies: Array<{ connection: string; source: string; token: string; teams: string[] }> = [];
const replies: Array<{ url: string; body: Record<string, unknown>; headers: Record<string, string> }> = [];
const state = {
eventsStatus: 200,
silent: false,
answer: (body: (typeof subscribes)[number]): Response => Response.json({ leases: body.watches.map((w) => ({ ...w, unit: "team-1", expiresAt: "2026-10-10T18:00:00Z" })), rejected: [] }),
/** Null: the service predates agent sessions and has no /v1/identify. */
identify: ((body: (typeof identifies)[number]): Response => Response.json({ user: { id: "u1", name: "Jane" }, teams: body.teams, rejected: [], expiresAt: "2026-10-10T18:00:00Z" })) as ((body: (typeof identifies)[number]) => Response) | null,
reply: (): Response => Response.json({ activity: "act-1" }),
};
const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit): Promise<Response> => {
const u = String(url);
Expand Down Expand Up @@ -52,12 +57,35 @@ function fakeHooks() {
subscribes.push(body);
return state.answer(body);
}
if (u === `${BASE}/v1/identify` && state.identify !== null) {
const body = JSON.parse(String(init?.body)) as (typeof identifies)[number];
identifies.push(body);
return state.identify(body);
}
if (u.startsWith(`${BASE}/v1/linear/sessions/`)) {
replies.push({ url: u, body: JSON.parse(String(init?.body)) as Record<string, unknown>, headers: { ...(init?.headers as Record<string, string>) } });
return state.reply();
}
return new Response("not found", { status: 404 });
}) as unknown as typeof fetch;
const hello = (connection: string, leaseSeconds = 3600) => `event: hello\ndata: ${JSON.stringify({ connection, leaseSeconds })}\n\n`;
const doorbell = (id: string, over: Record<string, unknown> = {}) =>
`id: 1\nevent: doorbell\ndata: ${JSON.stringify({ source: "linear", kind: "issue", id, unit: "team-1", action: "update", at: "2026-10-10T17:02:11Z", ...over })}\n\n`;
return { fetchImpl, streams, subscribes, state, hello, doorbell, last: () => streams.at(-1)! };
const session = (over: Record<string, unknown> = {}) =>
`id: 2\nevent: session\ndata: ${JSON.stringify({
source: "linear",
session: "sess-1",
action: "created",
issue: { id: "i-1", identifier: "ENG-1", team: "t-eng", teamKey: "ENG" },
asker: { id: "u2", name: "Carol" },
owner: { id: "u1", name: "Jane" },
fromOwner: false,
routedAs: "assignee",
comment: { text: "@bb build this", untrusted: true },
at: "2026-10-10T17:02:11Z",
...over,
})}\n\n`;
return { fetchImpl, streams, subscribes, identifies, replies, state, hello, doorbell, session, last: () => streams.at(-1)! };
}

describe("SSE parsing", () => {
Expand Down Expand Up @@ -160,8 +188,13 @@ describe("the loop", () => {
await vi.advanceTimersByTimeAsync(ms);
};

function start(hooks: ReturnType<typeof fakeHooks>, over: { leases?: () => Lease[]; token?: (account?: string) => Promise<string>; idleMs?: number } = {}) {
function start(
hooks: ReturnType<typeof fakeHooks>,
over: { leases?: () => Lease[]; token?: (account?: string) => Promise<string>; idleMs?: number; identity?: () => { account?: string; teams: string[] } | null } = {},
) {
const logs: string[] = [];
const sessions: SessionEvent[] = [];
const identities: IdentifyResponse[] = [];
const sweeps: string[] = [];
const doorbells: string[] = [];
const units: Array<string | null> = [];
Expand Down Expand Up @@ -195,11 +228,14 @@ describe("the loop", () => {
sweep: async (reason) => {
sweeps.push(reason);
},
...(over.identity === undefined ? {} : { identity: over.identity }),
onIdentified: (who) => void identities.push(who),
onSession: (event) => void sessions.push(event),
timing: { backoffMinMs: 1000, backoffMaxMs: 8000, ...(over.idleMs === undefined ? {} : { idleMs: over.idleMs }) },
});
const controller = new AbortController();
const done = loop.run(controller.signal);
return { loop, logs, sweeps, doorbells, units, rejected, controller, done, setToken: (t: string) => (token = t), refreshes: () => refreshes };
return { loop, logs, sweeps, doorbells, units, rejected, sessions, identities, controller, done, setToken: (t: string) => (token = t), refreshes: () => refreshes };
}

it("subscribes every watch on hello with the current token, sweeps, then rings on doorbells for issues only", async () => {
Expand Down Expand Up @@ -478,4 +514,118 @@ describe("the loop", () => {
s.controller.abort();
await s.done;
});

describe("agent sessions", () => {
it("identifies on hello and at every renewal with the current token and the teams, never logging the token", async () => {
const hooks = fakeHooks();
let teams = ["t-eng"];
const s = start(hooks, { identity: () => ({ teams }) });
await tick();
hooks.last().send(hooks.hello("c_1", 600));
await tick();
expect(hooks.identifies).toEqual([{ connection: "c_1", source: "linear", token: "tok-1", teams: ["t-eng"] }]);
expect(s.identities.map((i) => i.user.name)).toEqual(["Jane"]);

// The teams changed: identify again now, replacing the set.
teams = ["t-eng", "t-ops"];
await s.loop.reidentify();
expect(hooks.identifies.at(-1)).toMatchObject({ connection: "c_1", teams: ["t-eng", "t-ops"] });

s.setToken("tok-2");
await tick(300_000);
expect(hooks.identifies.at(-1)).toMatchObject({ token: "tok-2" });
expect(hooks.identifies).toHaveLength(3);
expect(s.logs.join("\n")).not.toMatch(/tok-/u);
s.controller.abort();
await s.done;
});

it("refreshes the token once when Linear refused it, and identifies nobody when there is no identity", async () => {
const hooks = fakeHooks();
hooks.state.identify = (body) => (body.token === "tok-1" ? new Response("token refused", { status: 401 }) : Response.json({ user: { id: "u1", name: "Jane" }, teams: [], rejected: [] }));
const s = start(hooks, { identity: () => ({ teams: [] }) });
await tick();
hooks.last().send(hooks.hello("c_1"));
await tick();
expect(hooks.identifies.map((i) => i.token)).toEqual(["tok-1", "tok-fresh-1"]);
expect(s.identities).toHaveLength(1);
s.controller.abort();
await s.done;

const none = fakeHooks();
const t = start(none, { identity: () => null });
await tick();
none.last().send(none.hello("c_2"));
await tick();
expect(none.identifies).toEqual([]);
expect(none.subscribes).toHaveLength(1);
t.controller.abort();
await t.done;
});

it("keeps the watches on a service without /v1/identify, saying so once", async () => {
const hooks = fakeHooks();
hooks.state.identify = null;
const s = start(hooks, { identity: () => ({ teams: [] }) });
await tick();
hooks.last().send(hooks.hello("c_1", 600));
await tick();
await tick(300_000);
expect(hooks.subscribes).toHaveLength(2);
expect(s.loop.connected).toBe(true);
expect(s.logs.filter((l) => l.includes("no /v1/identify"))).toHaveLength(1);
expect(s.sweeps).toEqual(["connected"]);
s.controller.abort();
await s.done;
});

it("hands session events on, parsed, and drops ones it cannot read", async () => {
const hooks = fakeHooks();
const s = start(hooks);
await tick();
hooks.last().send(hooks.hello("c_1"));
hooks.last().send(hooks.session());
hooks.last().send(hooks.session({ action: "stopped" }));
hooks.last().send("event: session\ndata: not json\n\n");
hooks.last().send(hooks.session({ session: "sess-2", action: "prompted", fromOwner: true, asker: { id: "u1", name: "Jane" }, comment: { text: "yes", untrusted: false } }));
await tick();
expect(s.sessions.map((e) => [e.session, e.action, e.issue.identifier, e.comment.untrusted])).toEqual([
["sess-1", "created", "ENG-1", true],
["sess-2", "prompted", "ENG-1", false],
]);
expect(s.logs.filter((l) => l.includes("does not understand"))).toHaveLength(1);
expect(s.doorbells).toEqual([]);
s.controller.abort();
await s.done;
});

it("replies over the current connection with no token, and refuses without one", async () => {
const hooks = fakeHooks();
const s = start(hooks);
await expect(s.loop.reply("sess-1", { kind: "response", body: "Done." }, new AbortController().signal)).rejects.toThrow(/not connected to bb-gate-hooks/u);
await tick();
hooks.last().send(hooks.hello("c_1"));
await tick();
expect(await s.loop.reply("sess/1", { kind: "elicitation", body: "Confirm?", externalUrl: "https://bb.example/t" }, new AbortController().signal)).toMatchObject({ activity: "act-1" });
expect(hooks.replies).toEqual([
{ url: `${BASE}/v1/linear/sessions/sess%2F1/activity`, body: { connection: "c_1", kind: "elicitation", body: "Confirm?", externalUrl: "https://bb.example/t" }, headers: expect.not.objectContaining({ authorization: expect.anything() }) },
]);
expect(JSON.stringify(hooks.replies)).not.toMatch(/tok-/u);

hooks.state.reply = () => Response.json({ error: "not-routed" }, { status: 403 });
const refused = await s.loop.reply("sess-1", { kind: "response", body: "x" }, new AbortController().signal).catch((e: unknown) => e);
expect(refused).toBeInstanceOf(HooksRequestError);
expect((refused as HooksRequestError).code).toBe("not-routed");
s.controller.abort();
await s.done;
});
});
});

describe("postActivity", () => {
it("leaves out an absent external link", async () => {
const hooks = fakeHooks();
await postActivity(hooks.fetchImpl, BASE, "c_1", "sess-1", { kind: "error", body: "No." }, new AbortController().signal);
expect(hooks.replies[0]!.body).toEqual({ connection: "c_1", kind: "error", body: "No." });
});
});
Loading
Loading