Public: anyone can read this; the crew can change it.

Talk's origins answers tidily: repos finds the account without an id, a page of one-line rows with the total #16402

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

talk/origins-tidy → main 0 commits

  • Merged. talk/origins-tidy was merged into main as 479b76d.

Review

Sign in to review this change.
4 files changed +196 −43
docs/features/talk.md +3 −1
@@ -182,7 +182,9 @@ accounts and what they hold; syncing one or changing its hosts stays on that
182182 page. A repository brought in from one is a mirror, which is not the off-box
183183 snapshot mirror of the forge's backups. `GET /api/v1/user/origins/:id/repos`
184184 takes the same `q`, and the terminal's migrate filter matches the same way
185 (name or description). Test: `test/talk-origins.test.ts`.
185 (name or description). `repos` answers `{ total, items, next_cursor }`: 50 one-line items a
186 page (`owner/name · private · fork · here as you/name`), every field with `full: true`, and no
187 account to name when you have one. Test: `test/talk-origins.test.ts`.
186188
187189 ## Receipts
188190
src/http/mcp/tools/origins.ts +79 −30
@@ -7,6 +7,33 @@ import { REPO_GROUPS, type RepoGroup } from "../../../origins/types.ts";
77 import type { Ctx } from "../../context.ts";
88 import { trustedHosts } from "../trusted_hosts.ts";
99 import { good, bad, type Args, type Tool } from "../shared.ts";
10 import type { OriginRepoRow } from "../../../core/origins.ts";
11 import type { User } from "../../../core/users.ts";
12
13 /** Rows a `repos` answer holds at most: a whole account's list once flooded the conversation. */
14 const REPOS_PAGE = 50;
15
16 /** One repository on one line: its name, who can see it, and its copy here when there is one. */
17 const repoLine = (ctx: Ctx, row: OriginRepoRow): string => {
18 const here = remoteRepoJson(ctx, row).mirroredAs;
19 return [row.fullName, row.private ? "private" : "public", ...(row.fork ? ["fork"] : []), ...(here === null ? [] : [`here as ${here.owner}/${here.name}`])].join(" · ");
20 };
21
22 /**
23 * The origin `repos` reads: the `id` given, or the one account a word names (`github`, a host),
24 * or with none the person's only account. Several and no word: they are named, in one line.
25 */
26 function originFor(ctx: Ctx, user: User, id: unknown): { id: string } | ReturnType<typeof bad> {
27 const mine = listUserOrigins(ctx.app, user);
28 const word = typeof id === "string" ? id.trim().toLowerCase() : "";
29 if (word !== "" && mine.some((o) => o.id === id)) return { id: id as string };
30 const host = (o: (typeof mine)[number]) => (URL.parse(o.webUrl)?.host ?? "").toLowerCase();
31 const named = word === "" ? mine : mine.filter((o) => o.kind === word || host(o) === word || host(o).split(".")[0] === word);
32 if (named.length === 1) return { id: named[0]!.id };
33 if (mine.length === 0) return bad("not_found", "no account elsewhere is connected; connect one on /settings/origins");
34 const list = (named.length > 1 ? named : mine).map((o) => `${o.login} on ${host(o)} (${o.id})`).join(", ");
35 return bad(word === "" || named.length > 1 ? "invalid" : "not_found", `say which account: \`id\` one of ${list}`);
36 }
1037
1138 /** `list` and `repos` only read what the person connected. */
1239 const reads = (args: Args): boolean => args["action"] === "list" || args["action"] === "repos";
@@ -24,7 +51,7 @@ const refusal = (ctx: Ctx, args: Args) =>
2451
2552 export const tool: Tool = {
2653 name: "origins",
27 doc: "`{ action, id?, group?, q?, hosts? }`: your GitHub and other forge accounts (`/settings/origins`): `list` them, `repos` one holds (`id`; `q` words; `mirroredAs` is the copy here; with `group` yours, shared or public, one page and `next_cursor`, sent back as `cursor`), `inventory` what each holds and its migration state, `sync` one now, or `hosts`: with none, read an origin's internal hosts (a forge admin), with `hosts` (one per line) replace them; as `GET /api/v1/user/origins`, `…/:id/repos` and `POST …/:id/sync`, for you only, an admin token (Talk reads `list` and `repos`); never a credential",
54 doc: "`{ action, id?, group?, q?, hosts? }`: your GitHub and other forge accounts (`/settings/origins`): `list` them, `repos` one holds (`id`, or a word like `github`, or none with one account; `q` words; 50 one-line rows a page, `full` for every field, `total` and `next_cursor`, sent back as `cursor`; `group` yours, shared or public, as the origin pages it), `inventory` what each holds and its migration state, `sync` one now, or `hosts`: with none, read an origin's internal hosts (a forge admin), with `hosts` (one per line) replace them; as `GET /api/v1/user/origins`, `…/:id/repos` and `POST …/:id/sync`, for you only, an admin token (Talk reads `list` and `repos`); never a credential",
2855 description:
2956 "Your GitHub and other forge accounts, and their repos.",
3057 inputSchema: {
@@ -35,6 +62,7 @@ export const tool: Tool = {
3562 group: { type: "string", enum: [...REPO_GROUPS] },
3663 q: { type: "string" },
3764 cursor: { type: "string" },
65 full: { type: "boolean" },
3866 hosts: { type: "string" },
3967 },
4068 required: ["action"],
@@ -43,7 +71,7 @@ export const tool: Tool = {
4371 // Its reads (the origins, what one holds, its inventory, the hosts with none given) are never
4472 // held for a Do it: only a sync and a hosts change are.
4573 heldNotWhen: (args) => reads(args) || args["action"] === "inventory" || (args["action"] === "hosts" && args["hosts"] === undefined),
46 readsWithout: ["id", "hosts", "cursor"],
74 readsWithout: ["id", "hosts", "cursor", "full"],
4775 // Talk's agent is never offered a Do it the tool can only refuse.
4876 refusesFirst: (ctx, _user, args) => refusal(ctx, args),
4977 async run(ctx, user, args) {
@@ -52,43 +80,64 @@ export const tool: Tool = {
5280 if (action === "hosts") return trustedHosts(ctx, user, args);
5381 if (action !== "list" && action !== "repos" && action !== "inventory" && action !== "sync")
5482 return bad("bad_action", "`action` is list, repos, inventory, sync or hosts");
55 if (action !== "list" && (typeof id !== "string" || id === ""))
83 if (action !== "list" && action !== "repos" && (typeof id !== "string" || id === ""))
5684 return bad("invalid", "send the origin's `id`, from list");
5785 const refused = refusal(ctx, args);
5886 if (refused !== undefined) return refused;
5987 if (action === "list")
6088 return good(listUserOrigins(ctx.app, user).map(originJson));
89 if (action === "repos") {
90 const found = originFor(ctx, user, id);
91 return "id" in found ? repos(ctx, user, found.id, args) : found;
92 }
6193 const origin = id as string;
6294 if (action === "sync") {
6395 const synced = await syncOriginNow(ctx.app, user, origin);
6496 return synced.ok ? good(synced.value) : bad("not_found", "no such origin");
6597 }
66 if (action === "inventory") {
67 const rows = await inventoryFor(ctx.app, user, origin);
68 return rows.ok
69 ? good(rows.value)
70 : rows.error === "unreachable"
71 ? bad("origin_unreachable", ORIGIN_UNREACHABLE)
72 : bad("not_found", "no such origin");
73 }
74 const q = typeof args["q"] === "string" ? args["q"] : undefined;
75 const unreachable = (error: string) =>
76 error === "unreachable" ? bad("origin_unreachable", ORIGIN_UNREACHABLE) : bad("not_found", "no such origin");
77 const group = args["group"];
78 if (typeof group === "string") {
79 // One page of the group, as the origin searched it (a forge searches `q` itself): its rows are
80 // never filtered again here, and `next_cursor` says there are more, sent back as `cursor`.
81 const cursor = typeof args["cursor"] === "string" && args["cursor"] !== "" ? args["cursor"] : undefined;
82 const page = await listOriginRepoGroup(ctx.app, user, origin, group as RepoGroup, {
83 ...(q === undefined ? {} : { q }),
84 ...(cursor === undefined ? {} : { cursor }),
85 });
86 if (!page.ok) return unreachable(page.error);
87 return good({ items: page.value.items.map((row) => remoteRepoJson(ctx, row)), next_cursor: page.value.next });
88 }
89 // Every page, from the picker's cache: `q` narrows it here.
90 const listed = await listRemoteRepos(ctx.app, user, origin);
91 if (!listed.ok) return unreachable(listed.error);
92 return good(listed.value.filter((row) => repoMatches(row, q)).map((row) => remoteRepoJson(ctx, row)));
98 const rows = await inventoryFor(ctx.app, user, origin);
99 return rows.ok
100 ? good(rows.value)
101 : rows.error === "unreachable"
102 ? bad("origin_unreachable", ORIGIN_UNREACHABLE)
103 : bad("not_found", "no such origin");
93104 },
94105 };
106
107 /**
108 * What an origin holds, a page at a time: one line a repository (`full` for every field), at most
109 * `REPOS_PAGE`, with `next_cursor` while more follow and, from the cache, `total`.
110 */
111 async function repos(ctx: Ctx, user: User, origin: string, args: Args) {
112 const q = typeof args["q"] === "string" ? args["q"] : undefined;
113 const cursor = typeof args["cursor"] === "string" && args["cursor"] !== "" ? args["cursor"] : undefined;
114 const shown = (rows: readonly OriginRepoRow[]) => rows.map((row) => (args["full"] === true ? remoteRepoJson(ctx, row) : repoLine(ctx, row)));
115 const unreachable = (error: string) =>
116 error === "unreachable" ? bad("origin_unreachable", ORIGIN_UNREACHABLE) : bad("not_found", "no such origin");
117 // A list read whole is paged here, its cursor `o:<rows before>`; an origin's own page (a forge's,
118 // at most 50) keeps the origin's cursor.
119 const ours = cursor?.startsWith("o:") === true;
120 const local = ours ? Math.max(0, Number.parseInt(cursor!.slice(2), 10) || 0) : 0;
121 const pageOf = (rows: readonly OriginRepoRow[], total: boolean) => {
122 const next = local + REPOS_PAGE < rows.length ? `o:${String(local + REPOS_PAGE)}` : null;
123 return good({ ...(total ? { total: rows.length } : {}), items: shown(rows.slice(local, local + REPOS_PAGE)), next_cursor: next });
124 };
125 const group = args["group"];
126 if (typeof group === "string") {
127 // One page of the group, as the origin searched it (a forge searches `q` itself): its rows are
128 // never filtered again here, and `next_cursor` says there are more, sent back as `cursor`.
129 const page = await listOriginRepoGroup(ctx.app, user, origin, group as RepoGroup, {
130 ...(q === undefined ? {} : { q }),
131 ...(cursor === undefined || ours ? {} : { cursor }),
132 });
133 if (!page.ok) return unreachable(page.error);
134 // No `next` from the origin: the group came back whole (GitHub's, cut from the cached list),
135 // so it is paged here; a forge's own page already holds at most 50 and keeps its cursor.
136 if (page.value.next === null) return pageOf(page.value.items, false);
137 return good({ items: shown(page.value.items), next_cursor: page.value.next });
138 }
139 // Every page, from the picker's cache: `q` narrows it here.
140 const listed = await listRemoteRepos(ctx.app, user, origin);
141 if (!listed.ok) return unreachable(listed.error);
142 return pageOf(listed.value.filter((row) => repoMatches(row, q)), true);
143 }
test/mcp-origins.test.ts +3 −3
@@ -103,9 +103,9 @@ describe("MCP origins", () => {
103103 });
104104
105105 test("lists its repositories and starts a sync", async () => {
106 const repos = await tool(aliceAdmin, { action: "repos", id: originId });
107 expect(repos.value.map((x: any) => x.fullName)).toEqual(["octo/sprockets"]);
108 expect(repos.value[0].mirroredAs).toBeNull();
106 const repos = await tool(aliceAdmin, { action: "repos", id: originId, full: true });
107 expect(repos.value.items.map((x: any) => x.fullName)).toEqual(["octo/sprockets"]);
108 expect(repos.value.items[0].mirroredAs).toBeNull();
109109 expect(repos.text).not.toContain(TOKEN);
110110 const sync = await tool(aliceAdmin, { action: "sync", id: originId });
111111 expect(sync.value).toBeDefined();
test/talk-origins.test.ts +111 −9
@@ -8,6 +8,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
88 import { mkdtemp, rm } from "node:fs/promises";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
11 import { createRepo } from "../src/actions/repos.ts";
1112 import { createApp, type App } from "../src/app.ts";
1213 import {
1314 appendTurn,
@@ -19,6 +20,7 @@ import { createUser, type User } from "../src/core/users.ts";
1920 import { mintViaToken } from "../src/core/via_token.ts";
2021 import { serve, type Servers } from "../src/http/server.ts";
2122 import { newFakeState, serveFakeForge, type FakeForge } from "./fake-origin.ts";
23 import { promote } from "./helpers/members.ts";
2224
2325 const LOGIN = "octo";
2426 const TOKEN = "octo-origin-secret-7c1e";
@@ -92,6 +94,7 @@ beforeAll(async () => {
9294 ? `acme/shared-${String(i)}`
9395 : `octo/sprocket-${String(i)}`,
9496 description: i === 42 ? "the answer" : "",
97 fork: i === 7,
9598 cloneUrl: `http://127.0.0.1:1/octo/r${String(i)}.git`,
9699 defaultBranch: "main",
97100 private: true,
@@ -155,7 +158,7 @@ describe("Talk's agent reads the person's own origins", () => {
155158 expect(list.value.map((o: { id: string }) => o.id)).toEqual([originId]);
156159 expect(list.text).not.toContain(TOKEN);
157160 const repos = await call(t.token, { action: "repos", id: originId });
158 expect(repos.value.length).toBeGreaterThan(0);
161 expect(repos.value.items.length).toBeGreaterThan(0);
159162 expect(repos.text).not.toContain(TOKEN);
160163 const turns = listTurns(app.db, alice.id, t.id, { limit: 50 });
161164 expect(turns.ok && turns.value.filter((x) => x.role === "confirm")).toEqual(
@@ -213,15 +216,15 @@ describe("repos is everything GitHub lists, narrowed by group and q", () => {
213216 ).toBeUndefined();
214217 // Read with the admin token, so on the trunk this fails on the count alone.
215218 const all = await call(admin, { action: "repos", id: originId });
216 expect(all.value?.length).toBe(MANY);
219 expect(all.value?.total).toBe(MANY);
217220 });
218221
219222 test("q narrows by name or description, and group splits yours from shared", async () => {
220223 const t = talk(alice, "find sprocket-14 on GitHub").token;
221224 expect(
222225 names(
223 (await call(t, { action: "repos", id: originId, q: "sprocket-14" }))
224 .value,
226 (await call(t, { action: "repos", id: originId, q: "sprocket-14", full: true }))
227 .value.items,
225228 ).sort(),
226229 ).toEqual([
227230 "octo/sprocket-14",
@@ -237,12 +240,12 @@ describe("repos is everything GitHub lists, narrowed by group and q", () => {
237240 ]);
238241 expect(
239242 names(
240 (await call(t, { action: "repos", id: originId, q: "the answer" }))
241 .value,
243 (await call(t, { action: "repos", id: originId, q: "the answer", full: true }))
244 .value.items,
242245 ),
243246 ).toEqual(["octo/sprocket-42"]);
244247 const shared = names(
245 (await call(t, { action: "repos", id: originId, group: "shared" })).value
248 (await call(t, { action: "repos", id: originId, group: "shared", full: true })).value
246249 .items,
247250 );
248251 expect(shared.length).toBe(MANY / 10);
@@ -254,6 +257,7 @@ describe("repos is everything GitHub lists, narrowed by group and q", () => {
254257 id: originId,
255258 group: "yours",
256259 q: "shared",
260 full: true,
257261 })
258262 ).value.items,
259263 );
@@ -304,7 +308,7 @@ describe("a forge origin's group is paged by the origin, and the agent is told t
304308 let cursor: string | null = null;
305309 let pages = 0;
306310 do {
307 const page = (await call(t, { action: "repos", id, group: "yours", ...(cursor === null ? {} : { cursor }) })).value as { items: { fullName: string }[]; next_cursor: string | null };
311 const page = (await call(t, { action: "repos", id, group: "yours", full: true, ...(cursor === null ? {} : { cursor }) })).value as { items: { fullName: string }[]; next_cursor: string | null };
308312 expect(page.items.length).toBeLessThanOrEqual(2);
309313 seen.push(...names(page.items));
310314 cursor = page.next_cursor === null ? null : page.next_cursor.trim();
@@ -313,7 +317,105 @@ describe("a forge origin's group is paged by the origin, and the agent is told t
313317 expect(seen.sort()).toEqual(["ana/gear-1", "ana/gear-2", "ana/gear-3", "ana/gear-4", "ana/gear-5"]);
314318 expect(pages).toBe(3);
315319 // `q` is the origin's search: its answer is not filtered again.
316 const named = (await call(t, { action: "repos", id, group: "yours", q: "gear-4" })).value as { items: { fullName: string }[] };
320 const named = (await call(t, { action: "repos", id, group: "yours", q: "gear-4", full: true })).value as { items: { fullName: string }[] };
317321 expect(names(named.items)).toEqual(["ana/gear-4"]);
318322 });
319323 });
324
325 describe("a listing never floods the conversation, and the account is found without an id", () => {
326 test("50 one-line rows a page, the total, and next_cursor until every one is read", async () => {
327 const t = talk(alice, "all my GitHub repos").token;
328 const first = (await call(t, { action: "repos", id: originId })).value as { total: number; items: string[]; next_cursor: string | null };
329 expect(first.total).toBe(MANY);
330 expect(first.items.length).toBe(50);
331 expect(first.items.every((line) => typeof line === "string" && /^\S+\/\S+ · (private|public)/.test(line.trim()))).toBe(true);
332 const seen = [...first.items];
333 let cursor = first.next_cursor?.trim() ?? null;
334 while (cursor !== null) {
335 const page = (await call(t, { action: "repos", id: originId, cursor })).value as { items: string[]; next_cursor: string | null };
336 seen.push(...page.items);
337 cursor = page.next_cursor?.trim() ?? null;
338 }
339 expect(new Set(seen.map((l) => l.trim().split(" ")[0])).size).toBe(MANY);
340 // A page's worth of lines is a small answer: a full list once came to about 92,000 characters.
341 expect(JSON.stringify(first).length).toBeLessThan(5_000);
342 });
343
344 test("with one account, no id reads it; a word names one of several; several and no word are named in one line", async () => {
345 const t = talk(alice, "which repos can you see on GitHub?").token;
346 // Alice has GitHub and, from the Forgejo test above, a second account: `github` names the first.
347 const byWord = (await call(t, { action: "repos", id: "github", q: "sprocket-149" })).value as { total: number };
348 expect(byWord.total).toBe(1);
349 const neither = await call(t, { action: "repos" });
350 // One line names them all (the fence around a via token's text adds the line breaks around it).
351 expect(neither.error).toMatch(/say which account: `id` one of octo on [^\n]*, ana on [^\n]*/);
352 // Bob has none: he is told where to connect one.
353 expect((await call(talk(bob, "my GitHub").token, { action: "repos" })).error).toContain("/settings/origins");
354 // One account: no id needed.
355 const carol = await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase" });
356 if (!carol.ok) throw new Error(carol.error);
357 promote(app.db, carol.value);
358 // Her own GitHub account: an account elsewhere is connected to one person here.
359 const hers = newFakeState("github", "carol-gh", "carol-origin-secret-81c2");
360 hers.repos.push({ id: 900, fullName: "carol-gh/notes", cloneUrl: "http://127.0.0.1:1/carol-gh/notes.git", defaultBranch: "main" });
361 const carolForge = serveFakeForge(hers);
362 try {
363 const res = await fetch(`${servers.url}/api/v1/user/origins`, {
364 method: "POST",
365 headers: { "content-type": "application/json", authorization: `Bearer ${createToken(app.db, carol.value.id, "admin", "admin").token}` },
366 body: JSON.stringify({ host: carolForge.url, kind: "github", token: "carol-origin-secret-81c2" }),
367 });
368 expect(res.status).toBe(201);
369 const only = (await call(talk(carol.value, "my GitHub repos").token, { action: "repos" })).value as { total: number; items: string[] };
370 expect(only.total).toBe(1);
371 expect(only.items[0]!.trim()).toStartWith("carol-gh/notes · public");
372 } finally {
373 carolForge.stop();
374 }
375 });
376 });
377
378 describe("the one-line rows and the pages, read as the agent reads them", () => {
379 const lines = (v: unknown) => (v as { items: string[] }).items.map((l) => l.trim());
380
381 test("a line says fork, and here as owner/name for a repository mirrored here", async () => {
382 const made = await createRepo(app, alice, { name: "sprocket-3", visibility: "private" });
383 if (!made.ok) throw new Error(String(made.error));
384 app.db.query("UPDATE repo SET origin_id = ?1, origin_remote_id = '3' WHERE id = ?2").run(originId, made.value.id);
385 const t = talk(alice, "my GitHub repos").token;
386 expect(lines((await call(t, { action: "repos", id: originId, q: "sprocket-7" })).value)).toContain("octo/sprocket-7 · private · fork");
387 expect(lines((await call(t, { action: "repos", id: originId, q: "sprocket-71" })).value)).toEqual(["octo/sprocket-71 · private"]);
388 expect(lines((await call(t, { action: "repos", id: originId, q: "sprocket-3" })).value)).toContain("octo/sprocket-3 · private · here as alice/sprocket-3");
389 });
390
391 test("full: true without a group answers objects, a group without full answers strings", async () => {
392 const t = talk(alice, "my GitHub repos").token;
393 const full = (await call(t, { action: "repos", id: originId, q: "sprocket-149", full: true })).value as { items: { fullName: string }[] };
394 expect(full.items.map((r) => r.fullName.trim())).toEqual(["octo/sprocket-149"]);
395 const shared = (await call(t, { action: "repos", id: originId, group: "shared" })).value as { items: unknown[] };
396 expect(shared.items.every((l) => typeof l === "string")).toBe(true);
397 expect(shared.items.length).toBe(MANY / 10);
398 });
399
400 test("a group read whole (GitHub's) is paged here with an o: cursor, to the end", async () => {
401 const t = talk(alice, "my own GitHub repos").token;
402 const seen: string[] = [];
403 let cursor: string | null = null;
404 let pages = 0;
405 do {
406 const page = (await call(t, { action: "repos", id: originId, group: "yours", ...(cursor === null ? {} : { cursor }) })).value as { items: string[]; next_cursor: string | null };
407 seen.push(...lines(page));
408 cursor = page.next_cursor === null ? null : page.next_cursor.trim();
409 if (cursor !== null) expect(cursor).toStartWith("o:");
410 pages++;
411 } while (cursor !== null && pages < 10);
412 expect(pages).toBe(3);
413 expect(new Set(seen).size).toBe(MANY - MANY / 10);
414 });
415
416 test("a word that names no account is not found, and the accounts are listed", async () => {
417 const r = await call(talk(alice, "my gitlab repos").token, { action: "repos", id: "gitlab" });
418 expect(r.error).toContain("not_found");
419 expect(r.error).toMatch(/say which account: `id` one of octo on [^\n]*/);
420 });
421 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs