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

A /talk line that starts with a slash runs a short command: /issue, /pull, /wallet #13982

Merged opened this

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

Merged

scout/forge:scout/13971-a-talk-line-that-starts-with-a-slash-run → main 5 commits fork 3 threads · 3 unresolved

  • Merged. scout/13971-a-talk-line-that-starts-with-a-slash-run was merged into main as d226509.

Review

Sign in to review this change.
5 files changed +274 −1
docs/features/README.md +1
@@ -153,6 +153,7 @@ Read with the guide page [Tell the crew](../guide-tell-the-crew.md).
153153 - [Share to the forge from a phone](share-to-the-forge.md)
154154 - [Since you were here](since-you-were-here.md)
155155 - [/talk answers "what needs me?"](talk-decisions.md)
156 - [/talk slash commands: /issue, /pull, /wallet](talk-slash.md)
156157 - [Talk as a builder](talk-builder.md)
157158 - [Answering a proposed action: Do it and Not now](talk-answer-action.md)
158159 - [/talk attachments](talk-attachments.md)
docs/features/talk-slash.md added +13
@@ -0,0 +1,13 @@
1 # /talk slash commands (#13971)
2
3 A /talk line that starts with a slash and a letter runs a short command: no model turn, no cost, nothing written but the two turns. Every command only reads.
4
5 - `/issue N`, `/pull N`: `owner/repo#N: title`, its state and author, the first 600 characters of the body, and its page.
6 - `/wallet`: the repository's balance line and its three latest spends, the words of its wallet page.
7 - **Which words are shared:** only the facts, not the page's rendering. The issue and pull answers use the same title, state and author fields as their pages (read through `getIssue`/`getPull`), and `/wallet` uses `readWalletSummary`, the page's own reader, so its balance and spend lines are the page's words. The layout, labels and the body's markdown are not: the body is plain text cut at 600 characters.
8 - **Which repository:** `owner/repo` typed in the line (`/issue owner/repo#7`, `/wallet owner/repo`), else the one the chat is about (`/talk?about=`).
9 - **Read as you:** a repository or number you cannot read answers `Not found.`, as its page does.
10 - **Unknown command:** says so and lists the table.
11 - **Both doors:** the terminal's `talk` goes through the same `say()`, so it answers the same words (`src/actions/talk_slash.ts`).
12 - **Left out:** commands that write, and a default repository when none is named.
13 - **Queued:** a slash line sent while an answer runs waits its turn, then is answered the same way, not handed to the model.
src/actions/talk_slash.ts added +90
@@ -0,0 +1,90 @@
1 /**
2 * A /talk line that starts with a slash runs a short, read-only command (#13971): `/issue N`,
3 * `/pull N`, `/wallet`. The answer reads the same fields as the page (title, state, who, body; the
4 * wallet's balance and latest spends) read as the signed-in person, so a repository they cannot
5 * read is `not found`, as on its page. Nothing is written but the two turns. Which repository: the
6 * one typed (`owner/repo`, or `owner/repo#N`), else the one the conversation is about.
7 */
8
9 import type { App } from "../app.ts";
10 import { getIssue } from "../core/issues.ts";
11 import { getPull } from "../core/pulls.ts";
12 import { canRead, getRepo, type Repo } from "../core/repos.ts";
13 import { mayViewId } from "../core/sealed.ts";
14 import { parseAbout } from "../core/talk_about.ts";
15 import type { User } from "../core/users.ts";
16 import { readWalletSummary } from "./wallet.ts";
17
18 /** The commands, as the unknown-command answer lists them. */
19 export const SLASH_COMMANDS: readonly (readonly [string, string])[] = [
20 ["/issue N", "an issue's title, state and body"],
21 ["/pull N", "a pull's title, state and body"],
22 ["/wallet", "the repository's balance and latest spends"],
23 ];
24
25 /** Where a typed repository is optional: `/issue 7 owner/repo` or `/issue owner/repo#7`. */
26 export const SLASH_USAGE = "Add the repository as owner/repo, or start the chat from a repository.";
27
28 /** Whether the line is a command: a slash, then a word. */
29 export const isSlash = (text: string): boolean => /^\/[A-Za-z]/.test(text.trim());
30
31 const table = (): string => ["Commands (read only):", ...SLASH_COMMANDS.map(([c, d]) => `${c}: ${d}`)].join("\n");
32
33 const BODY_MAX = 600;
34
35 /** The repository and number a command's arguments name, or a sentence saying what is missing. */
36 function target(app: App, user: User, args: readonly string[], about: string | null, wantNumber: boolean): { repo: Repo; number: number | null } | string {
37 let number: number | null = null;
38 let named = parseAbout(about);
39 for (const arg of args) {
40 if (/^#?[1-9][0-9]{0,8}$/.test(arg)) number = Number(arg.replace("#", ""));
41 else {
42 const p = parseAbout(arg);
43 if (p === null) return `${arg.slice(0, 60)} is not a repository (owner/repo) or a number.`;
44 named = p;
45 if (p.number !== undefined) number = p.number;
46 }
47 }
48 if (named === null) return SLASH_USAGE;
49 if (wantNumber && number === null) return "Give the number, like /issue 12.";
50 const repo = getRepo(app.db, named.owner, named.repo);
51 if (repo === undefined || !canRead(app.db, repo, user)) return "Not found.";
52 return { repo, number };
outdated

number! is a non-null assertion; restructure so the type carries the guarantee.

53 }
54
55 function change(app: App, user: User, kind: "issue" | "pull", args: readonly string[], about: string | null): string {
56 const t = target(app, user, args, about, true);
57 if (typeof t === "string") return t;
58 if (t.number === null) return "Give the number, like /issue 12.";
59 const subject = kind === "pull" ? getPull(app.db, t.repo.id, t.number) : getIssue(app.db, t.repo.id, t.number);
60 if (subject === undefined || subject.kind !== kind || !mayViewId(app.db, t.repo, subject.id, user)) return "Not found.";
61 const body = subject.body.trim();
62 const shown = body.length > BODY_MAX ? `${body.slice(0, BODY_MAX)}…` : body;
63 const where = `/${t.repo.ownerName}/${t.repo.name}/${kind === "pull" ? "pulls" : "issues"}/${subject.number}`;
64 return [`${t.repo.ownerName}/${t.repo.name}#${subject.number}: ${subject.title}`, `${subject.state}, by ${subject.authorName}`, shown, where].filter((l) => l !== "").join("\n");
65 }
66
67 function wallet(app: App, user: User, args: readonly string[], about: string | null): string {
68 const t = target(app, user, args, about, false);
69 if (typeof t === "string") return t;
70 const read = readWalletSummary(app, user, t.repo, new Date());
71 if (!read.ok) return "Not found.";
72 const w = read.value;
73 return [`Wallet of ${w.app}`, w.balance, ...(w.latest.length === 0 ? ["Nothing spent yet."] : w.latest), `/${t.repo.ownerName}/${t.repo.name}/wallet`].join("\n");
74 }
75
76 /** The answer to a slash line; an unknown command lists the table. */
77 export function slashAnswer(app: App, user: User, text: string, about: string | null): string {
78 const [word = "", ...args] = text.trim().split(/\s+/);
79 const rest = args.slice(0, 4);
80 switch (word.toLowerCase()) {
81 case "/issue":
82 return change(app, user, "issue", rest, about);
83 case "/pull":
84 return change(app, user, "pull", rest, about);
85 case "/wallet":
86 return wallet(app, user, rest, about);
87 default:
88 return `${word.slice(0, 40)} is not a command.\n${table()}`;
89 }
90 }
src/crew/conversation.ts +19 −1
@@ -20,6 +20,7 @@ import { join } from "node:path";
2020 import type { App } from "../app.ts";
2121 import { aboutContext } from "../core/talk_about.ts";
2222 import { asksWhatNeedsMe, decisionsAnswer } from "../actions/talk_decisions.ts";
23 import { isSlash, slashAnswer } from "../actions/talk_slash.ts";
2324 import { buildTurnEnded } from "../actions/build_pull.ts";
2425 import { buildLead, chatBuildOf } from "../core/chat_build.ts";
2526 import { getRepoById } from "../core/repos.ts";
@@ -240,6 +241,8 @@ export interface Queued {
240241 readonly id: string;
241242 readonly text: string;
242243 readonly files: readonly ConversationFile[];
244 /** The subject the chat is about, for a queued slash line to name its repository. */
245 readonly about?: string | null;
243246 }
244247
245248 /** Most messages that may wait behind one turn. */
@@ -283,10 +286,17 @@ function drain(app: App, options: ConversationOptions, conversation: Conversatio
283286 if (list?.length === 0) queues.delete(conversation.id);
284287 if (next === undefined) return;
285288 const userId = conversation.userId;
289 const user = getUserById(app.db, userId);
290 if (user === undefined) return;
286291 const current = getConversation(app.db, userId, conversation.id);
287292 if (current === undefined || current.archivedAt !== null) return void queues.delete(conversation.id);
288293 const stored = appendTurn(app.db, userId, current.id, { role: "person", text: next.text });
289294 if (!stored.ok) return drain(app, options, current);
295 // A queued slash line is answered as it would have been, not handed to the model.
296 if (next.files.length === 0 && isSlash(next.text)) {
297 appendTurn(app.db, userId, current.id, { role: "agent", text: slashAnswer(app, user, next.text, next.about ?? null) });
298 return drain(app, options, current);
299 }
290300 // A file taken back or sent some other way while this waited is left out, not sent twice.
291301 const files = next.files.filter((f) => {
292302 const now = fileOwnedBy(app.db, userId, f.id);
@@ -325,7 +335,7 @@ export function say(
325335 if (conversation === undefined) return err("not_found");
326336 if (during !== "inject" && live.has(conversation.id)) {
327337 const list = queues.get(conversation.id) ?? [];
328 const waiting: Queued = { id: id(), text, files };
338 const waiting: Queued = { id: id(), text, files, about: about ?? null };
329339 if (files.some((f) => fileQueued(f.id))) return err("file_taken");
330340 if (during === "queue") {
331341 if (list.length >= QUEUE_MAX) return err("queue_full");
@@ -346,6 +356,14 @@ export function say(
346356 appendTurn(app.db, userId, conversation.id, { role: "agent", text: answer });
347357 return ok({ how: "answered", answer });
348358 }
359 // A line that starts with a slash is a short read-only command: the page's words, no model turn.
360 if (!live.has(conversation.id) && files.length === 0 && isSlash(text)) {
361 const asked = appendTurn(app.db, userId, conversation.id, { role: "person", text });
362 if (!asked.ok) return err("too_long");
363 const answer = slashAnswer(app, user, text, about ?? null);
364 appendTurn(app.db, userId, conversation.id, { role: "agent", text: answer });
365 return ok({ how: "answered", answer });
366 }
349367 // The subject rides with a new conversation's first message only (#10496), as fenced data the
350368 // agent reads before the words.
351369 const first = listTurns(app.db, userId, conversation.id, { limit: 1 });
test/talk-slash.test.ts added +151
@@ -0,0 +1,151 @@
1 /** A /talk line that starts with a slash runs a short read-only command (#13971). */
2
3 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
4 import { chmodSync, writeFileSync } from "node:fs";
5 import { mkdtemp, rm } from "node:fs/promises";
6 import { tmpdir } from "node:os";
7 import { join } from "node:path";
8 import { createApp, type App } from "../src/app.ts";
9 import { openIssue } from "../src/actions/issues.ts";
10 import { openPull } from "../src/actions/pulls.ts";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { talk } from "../src/actions/talk.ts";
13 import { isSlash } from "../src/actions/talk_slash.ts";
14 import { listTurns, newConversation } from "../src/core/conversations.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { configureConversation, say, turnRunning } from "../src/crew/conversation.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 describe("talk slash commands", () => {
22 let dir = "";
23 let app: App;
24 let alice: User;
25 let bob: User;
26 let pullNumber = 0;
27
28 const answer = async (user: User, words: string, about?: string): Promise<string> => {
29 const conversation = newConversation(app.db, user.id);
30 const said = talk(app, user, words, [], "inject", conversation.id, about);
31 if (!said.ok) throw new Error(said.error);
32 await said.value.done;
33 const turns = listTurns(app.db, user.id, conversation.id);
34 if (!turns.ok) throw new Error("turns");
35 return turns.value.at(-1)!.text;
36 };
37
38 beforeAll(async () => {
39 dir = await mkdtemp(join(tmpdir(), "slash-"));
40 app = createApp({ dataDir: dir, port: 0, disk: () => ({ freeBytes: 95, totalBytes: 100 }) });
41 configureConversation(app, { binary: join(dir, "no-agent"), localUrl: "http://127.0.0.1:1", budgetUsd: 1, timeoutMs: 5_000, signal: new AbortController().signal });
42 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-long-talk-slash-pass", adminIfFirst: true });
43 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-long-talk-slash-pass" });
44 if (!a.ok || !b.ok) throw new Error("users");
45 alice = a.value;
46 bob = b.value;
47 const made = await createRepo(app, alice, { name: "lab", visibility: "private" });
48 if (!made.ok) throw new Error(String(made.error));
49 const opened = openIssue(app, alice, made.value, { title: "Slash me", body: "The body words" });
50 if (!opened.ok) throw new Error(String(opened.error));
51 const seeded = await commitToBranch(app, alice, made.value, { message: "Start", files: [{ path: "README.md", content: "# lab\n" }] });
52 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
53 const pushed = await commitToBranch(app, alice, made.value, { branch: "feature/x", base: "main", message: "x", files: [{ path: "x.ts", content: "export const x = 1;\n" }] });
54 if (!pushed.ok) throw new Error(JSON.stringify(pushed.error));
55 const pull = await openPull(app, alice, made.value, { title: "Add x", body: "Pull body words", baseBranch: "main", headBranch: "feature/x" });
56 if (!pull.ok) throw new Error(String(pull.error));
57 pullNumber = pull.value.number;
58 }, 30_000);
59 afterAll(async () => {
60 await rm(dir, { recursive: true, force: true });
61 });
62
outdated

This only proves /pull on an issue number is Not found. Add a test that opens a real pull and asserts its title, state and author in the /pull N answer.

63 test("a slash then a letter is a command", () => {
64 expect(isSlash("/issue 1")).toBe(true);
65 expect(isSlash("/ 1")).toBe(false);
66 expect(isSlash("//x")).toBe(false);
67 expect(isSlash("issue 1")).toBe(false);
68 });
69
70 test("/issue N answers with the issue's words", async () => {
71 const said = await answer(alice, "/issue 1", "alice/lab");
72 expect(said).toContain("alice/lab#1: Slash me");
73 expect(said).toContain("The body words");
74 expect(said).toContain("open, by alice");
75 });
76
77 test("/issue owner/repo#N names the repository itself", async () => {
78 expect(await answer(alice, "/issue alice/lab#1")).toContain("Slash me");
79 });
80
81 test("/pull N answers with the pull's title, state and author", async () => {
82 const said = await answer(alice, `/pull ${pullNumber}`, "alice/lab");
83 expect(said).toContain(`alice/lab#${pullNumber}: Add x`);
84 expect(said).toContain("open, by alice");
85 expect(said).toContain("Pull body words");
86 expect(said).toContain(`/alice/lab/pulls/${pullNumber}`);
87 });
88
89 test("/issue on a pull number, /pull on an issue number, and a missing number, are not found", async () => {
90 expect(await answer(alice, `/issue ${pullNumber}`, "alice/lab")).toBe("Not found.");
91 expect(await answer(alice, "/pull 1", "alice/lab")).toBe("Not found.");
92 expect(await answer(alice, "/issue 99", "alice/lab")).toBe("Not found.");
93 });
94
95 test("a repository the person cannot read is not found", async () => {
96 expect(await answer(bob, "/issue 1", "alice/lab")).toBe("Not found.");
97 expect(await answer(bob, "/wallet alice/lab")).toBe("Not found.");
98 });
99
100 test("/wallet answers with the balance", async () => {
101 const said = await answer(alice, "/wallet alice/lab");
102 expect(said).toContain("Wallet of alice/lab");
103 expect(said).toContain("Nothing spent yet.");
104 });
105
106 test("without a repository it says how to name one", async () => {
107 expect(await answer(alice, "/wallet")).toContain("owner/repo");
108 expect(await answer(alice, "/issue", "alice/lab")).toContain("/issue 12");
109 });
110
111 test("an unknown command lists the table", async () => {
112 const said = await answer(alice, "/frobnicate");
113 expect(said).toContain("/frobnicate is not a command.");
114 for (const c of ["/issue N", "/pull N", "/wallet"]) expect(said).toContain(c);
115 });
116
117 test("a slash line sent while an answer is running is queued, not run", async () => {
118 const bin = join(dir, "slow-agent");
119 writeFileSync(
120 bin,
121 `#!/bin/sh
122 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
123 IFS= read -r first
124 echo '{"type":"system","subtype":"init","session_id":"s-slash","model":"fake"}'
125 while [ ! -f "${dir}/release" ]; do sleep 0.05; done
126 echo '{"type":"result","subtype":"success","is_error":false,"result":"done","total_cost_usd":0.1,"num_turns":1,"session_id":"s-slash","terminal_reason":"completed","usage":{"input_tokens":1,"output_tokens":1}}'
127 `,
128 );
129 chmodSync(bin, 0o755);
130 const o = { binary: bin, localUrl: "http://127.0.0.1:9", budgetUsd: 1, timeoutMs: 30_000, signal: new AbortController().signal };
131 const conversation = newConversation(app.db, alice.id);
132 const first = say(app, o, alice.id, "think about it", [], "queue", conversation.id);
133 expect(first.ok && first.value.how).toBe("started");
134 const slash = say(app, o, alice.id, "/issue 1", [], "queue", conversation.id, "alice/lab");
135 expect(slash.ok && slash.value.how).toBe("queued");
136 const turns = listTurns(app.db, alice.id, conversation.id);
137 if (!turns.ok) throw new Error("turns");
138 expect(turns.value.map((t) => t.text)).not.toContain("/issue 1");
139 expect(turns.value.some((t) => t.text.includes("Slash me"))).toBe(false);
140 writeFileSync(join(dir, "release"), "");
141 // The queued line runs once the turn ends; wait for its answer so nothing outlives the test.
142 const answered = (): boolean => {
143 const t = listTurns(app.db, alice.id, conversation.id);
144 return t.ok && t.value.some((x) => x.role === "agent" && x.text.includes("Slash me")) && !turnRunning(app, alice.id, conversation.id);
145 };
146 for (let i = 0; i < 1200 && !answered(); i++) {
147 await Bun.sleep(25); // real-timer: waits for the stand-in agent process to exit after release
148 }
149 expect(answered()).toBe(true);
150 });
151 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs