Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Merge main: skills past the start of a message run only from a person's words

milind-soni9559f20e6927
diff --cc server/host/skills-library.ts
index 1b33334ffb,ef305056ff..89646b08f1
--- a/server/host/skills-library.ts
+++ b/server/host/skills-library.ts
@@@ -1,6 -1,7 +1,7 @@@
import { randomUUID } from "node:crypto";
import { join } from "node:path";
-import { skillCommandTurnText, skillMentions } from "../../shared/skill-command.ts";
++import { skillCalls, skillCommandTurnText } from "../../shared/skill-command.ts";
import type { SkillRequestCardData, SkillShareRecord } from "../../shared/skill-request.ts";
import { narrowestAudience, intersectAudience } from "../bot-visibility.ts";
import { DATA_DIR, type AppConfig } from "../config.ts";
@@@ -24,11 -25,9 +25,10 @@@ import
updateSharedLearnedSkill,
type ShareBot,
} from "../skill-share.ts";
- import { enabledSkillFile, listSkills, readSkillFile, resolveBotSkills, skillsSystemPrompt, type SkillListing } from "../skills.ts";
- import { expandSkillCommands, mayCallSkill } from "../../shared/skill-command.ts";
- import { typedWords } from "../typed-sends.ts";
+ import { enabledSkillFiles, listSkills, readSkillFile, resolveBotSkills, skillsSystemPrompt, type SkillListing } from "../skills.ts";
import type { BotRecord, Message, Store } from "../store.ts";
import { claudeUserSkillsEnabled } from "../turn-settings.ts";
++import { typedWords } from "../typed-sends.ts";
import { TASK_WORKSPACES_DIR } from "../workspace.ts";
type ReceiptArgs = {
@@@ -255,18 -254,23 +255,25 @@@ export function createSkillsLibraryHost
return importsFor(bot, conversationSkills(bot, threadId), instance);
},
- /** `/name` for one of the bot's own, library or imported skills, or one its engine loads by itself. `lines` are the
- * turn's own lines when it is a person's turn: only words they typed can call a skill past the start of the text. */
- /** Each `/name` in the message for one of the bot's own, library or imported skills, or one its engine loads by itself. */
- expandSkillCommand(bot: BotRecord, threadId: string, text: string, instance?: TurnInstance): string {
- const mentioned = skillMentions(text);
++ /** Each `/name` called for one of the bot's own, library or imported skills, or one its engine loads by itself. `lines`
++ * are the turn's own lines when it is a person's turn: only words they typed can call a skill past the start of the text. */
+ expandSkillCommand(bot: BotRecord, threadId: string, text: string, instance?: TurnInstance, lines: ReadonlyArray<{ sendId?: string; text?: string }> = []): string {
+ const typed = typedWords(threadId, lines);
- if (!mayCallSkill(text, typed)) return text;
++ const mentioned = skillCalls(text, typed);
+ if (!mentioned.length) return text;
const assigned = skillsLibraryEnabled(cfg) ? liveAssigned(bot) : undefined;
- const own = resolveBotSkills(bot.id, assigned);
- // A skill switched off on the Skills page stays off, even when the engine holds one of the same name.
- const switched = new Set([...own, ...importedSkillListings(bot.id, new Set())].filter((skill) => !skill.enabled).map((skill) => skill.name));
- const outside = [...importsFor(bot, assigned, instance), ...nativesFor(bot, threadId, instance).filter((skill) => !switched.has(skill.name))];
- const names = [...own.filter((skill) => skill.enabled), ...outside].map((skill) => skill.name);
- return expandSkillCommands(text, names, (name) => enabledSkillFile(bot.id, name, assigned) ?? outside.find((skill) => skill.name === name)?.file ?? null, typed);
+ const files = enabledSkillFiles(bot.id, mentioned, assigned);
+ const add = (skills: readonly ImportedSkillView[]) => {
+ for (const skill of skills) if (mentioned.includes(skill.name) && !files.has(skill.name)) files.set(skill.name, skill.file);
+ };
+ if (files.size < mentioned.length) add(importsFor(bot, assigned, instance));
+ if (files.size < mentioned.length) {
+ // A skill switched off on the Skills page stays off, even when the engine holds one of the same name.
+ const switched = new Set([...resolveBotSkills(bot.id, assigned), ...importedSkillListings(bot.id, new Set())]
+ .filter((skill) => !skill.enabled).map((skill) => skill.name));
+ add(nativesFor(bot, threadId, instance).filter((skill) => !switched.has(skill.name)));
+ }
- return skillCommandTurnText(text, files);
++ return skillCommandTurnText(text, files, typed);
},
shareNote(bot: BotRecord, threadId: string, enabled: boolean): TurnShareNote {
diff --cc server/imported-skills.test.ts
index f833a2fd1d,0a3c08ab53..80df17c6d7
--- a/server/imported-skills.test.ts
+++ b/server/imported-skills.test.ts
@@@ -6,10 -6,9 +6,10 @@@ import { afterEach, describe, expect, i
import { DATA_DIR, type AppConfig } from "./config.ts";
import { createSkillsLibraryHost } from "./host/skills-library.ts";
import {
- expandImportedSkillCommand, IMPORTED_CHANGED_WARNING, IMPORTED_SKILLS_DIR, importedSkillListings, importedSkillsFor, importedSkillsPrompt,
+ IMPORTED_CHANGED_WARNING, IMPORTED_SKILLS_DIR, importedSkillListings, importedSkillsFor, importedSkillsPrompt,
nativeSkillFolders, readImportedSkillFile, setImportedSkillEnabled, storeImportedSkills, syncImportedSkillLinks, type ImportedSkillInput,
} from "./imported-skills.ts";
- import { expandSkillCommands } from "../shared/skill-command.ts";
++import { skillCommandTurnText } from "../shared/skill-command.ts";
import { ensureTaskWorkspaceWithSkills } from "./skill-task-links.ts";
import { installSkill, setSkillEnabled } from "./skills.ts";
import type { BotRecord, Store } from "./store.ts";
@@@ -60,9 -58,8 +60,9 @@@ describe("skills brought in from this c
const prompt = importedSkillsPrompt(skills);
expect(prompt).toContain("Skills from this computer:");
expect(prompt).toContain(`- pdf: Works with pdf. Read ${JSON.stringify(join(IMPORTED_SKILLS_DIR, "pdf", "SKILL.md"))}.`);
- const fileOf = (name: string) => skills.find((skill) => skill.name === name)?.file ?? null;
- expect(expandSkillCommands("/review the diff", names(skills), fileOf)).toContain(`Read ${JSON.stringify(join(IMPORTED_SKILLS_DIR, "review", "SKILL.md"))}`);
- expect(expandSkillCommands("/other thing", names(skills), fileOf)).toBe("/other thing");
- expect(expandImportedSkillCommand("/review the diff", skills)).toContain(`Read ${JSON.stringify(join(IMPORTED_SKILLS_DIR, "review", "SKILL.md"))}`);
- expect(expandImportedSkillCommand("/other thing", skills)).toBe("/other thing");
++ const files = new Map(skills.map((skill) => [skill.name, skill.file]));
++ expect(skillCommandTurnText("/review the diff", files)).toContain(`Read ${JSON.stringify(join(IMPORTED_SKILLS_DIR, "review", "SKILL.md"))}`);
++ expect(skillCommandTurnText("/other thing", files)).toBe("/other thing");
const folder = ensureTaskWorkspaceWithSkills(bot, "thread-1", skills);
for (const family of [".claude", ".agents", ".grok"]) {
expect(target(join(folder, family, "skills", "pdf"))).toBe(resolve(IMPORTED_SKILLS_DIR, "pdf"));
@@@ -188,13 -185,5 +188,13 @@@
expect(host.readBotSkillFile(record, "skill-03")).toBe(skillMd("skill-03"));
expect(host.expandSkillCommand(record, "thread", "/skill-03 go", { instanceId: "claude", driverKind: "claudeAgent" })).toContain(`Read ${JSON.stringify(join(IMPORTED_SKILLS_DIR, "skill-03", "SKILL.md"))}`);
expect(host.expandSkillCommand(record, "thread", "/zeta-own go")).toContain(JSON.stringify(join("workspaces", bot, "skills", "zeta-own", "SKILL.md")).slice(1, -1));
+ // One message reaches both kinds, whichever comes first.
+ const sendId = randomUUID();
- const typed = "Two things\n/skill-03 the diff\n/zeta-own after it";
++ const typed = "Two things: /skill-03 the diff, /zeta-own after it";
+ noteTypedSend("thread", sendId, typed);
+ const both = host.expandSkillCommand(record, "thread", typed, { instanceId: "claude", driverKind: "claudeAgent" }, [{ sendId, text: typed }]);
+ expect(both).toContain(JSON.stringify(join(IMPORTED_SKILLS_DIR, "skill-03", "SKILL.md")));
+ expect(both).toContain(JSON.stringify(join("workspaces", bot, "skills", "zeta-own", "SKILL.md")).slice(1, -1));
- expect(both.endsWith(`Message: ${typed}`)).toBe(true);
++ expect(both.endsWith(`Request: ${typed}`)).toBe(true);
});
});
diff --cc server/native-skills.test.ts
index 9e2d0f57fc,03a2d4eabc..3e61a8f762
--- a/server/native-skills.test.ts
+++ b/server/native-skills.test.ts
@@@ -68,25 -67,10 +68,27 @@@ describe("skills the engine loads by it
expect(host.expandSkillCommand(bot, "main", "/growth-data-expert find churn")).toContain(`Read ${JSON.stringify(shared)}`);
expect(host.expandSkillCommand(bot, "main", "/bot-notes")).toContain(`Read ${JSON.stringify(own)}`);
expect(host.expandSkillCommand(bot, "main", "/mine go")).toContain(JSON.stringify(join("workspaces", bot.id, "skills", "mine")).slice(1, -1));
- const both = host.expandSkillCommand(bot, "main", "find churn with /growth-data-expert, then /mine");
+ });
+
- it("run from a later line a person typed, alongside the bot's own, and stay off when switched off", () => {
++ it("run mid-message from what a person typed, alongside the bot's own, and stay off when switched off", () => {
+ const { host, bot } = hostFor("claudeAgent");
+ const shared = plant(SHARED, "growth-data-expert");
+ plant(SHARED, "mine-off");
+ installSkill(bot.id, "local", [{ path: "SKILL.md", content: skillMd("mine") }]);
+ setSkillEnabled(bot.id, "mine", true);
+ installSkill(bot.id, "local", [{ path: "SKILL.md", content: skillMd("mine-off") }]);
+ const typed = (text: string) => {
+ const sendId = randomUUID();
+ noteTypedSend("main", sendId, text);
+ return host.expandSkillCommand(bot, "main", text, undefined, [{ sendId, text }]);
+ };
- const later = typed("/mine go\n/growth-data-expert find churn");
- expect(later).toContain(JSON.stringify(join("workspaces", bot.id, "skills", "mine")).slice(1, -1));
- expect(later).toContain(`The request also calls your growth-data-expert skill with /growth-data-expert (read ${JSON.stringify(shared)})`);
- expect(typed("Find churn\n/growth-data-expert")).toContain(`your growth-data-expert skill with /growth-data-expert (read ${JSON.stringify(shared)})`);
- expect(typed("Skip it\n/mine-off")).toBe("Skip it\n/mine-off");
++ const both = typed("find churn with /growth-data-expert, then /mine");
++ expect(both).toContain("ran 2 of your skills with /growth-data-expert, /mine");
+ expect(both).toContain(`${JSON.stringify(shared)} for /growth-data-expert`);
+ expect(both).toMatch(new RegExp(`workspaces.${bot.id}.skills.mine.SKILL\\.md" for /mine`));
+ expect(both).toContain("Request: find churn with /growth-data-expert, then /mine");
++ expect(typed("Skip it, /mine-off")).toBe("Skip it, /mine-off");
++ expect(host.expandSkillCommand(bot, "main", "find churn with /growth-data-expert")).toBe("find churn with /growth-data-expert");
});
it("stay out of a bot or team package, which carries only the bot's own, library and imported skills", () => {
diff --cc server/routes/bot-messages.test.ts
index 092c7b5e1a,49836a12e6..2607dbf077
--- a/server/routes/bot-messages.test.ts
+++ b/server/routes/bot-messages.test.ts
@@@ -162,35 -161,6 +162,35 @@@ async function fixture(desktopManaged
return { store, bot, threadId, state, post, edit, cancelQueued, show, row, sent, patches: vi.spyOn(store, "patchMessage") };
}
+describe("POST /api/bots/:id/messages and who typed it", () => {
- const words = "Look at this\n/standup it";
++ const words = "Look at this and /standup it";
+
+ it("takes a plain send from the desktop's own page as a person's", async () => {
+ const { threadId, post } = await fixture();
+ const plain = await post({ threadId, sendId: SEND, text: words });
+ expect(plain.status, JSON.stringify(plain.body)).toBe(202);
+ expect(typedWords(threadId, [plain.body.message])).toBe(words);
+ });
+
+ it("takes neither a press, whose words the widget wrote, nor a relay as a person's", async () => {
+ const { store, bot, threadId, post, show } = await fixture();
+ const pressed = await post({ threadId, sendId: SEND, text: words, widgetAction: { messageId: show("routineForm"), ref: "confirm", values: { days: "mon,tue,wed,thu,fri,sat,sun", report: "discord:releases" } } });
+ expect(pressed.status, JSON.stringify(pressed.body)).toBe(202);
+ expect(typedWords(threadId, [pressed.body.message])).toBe("");
+ store.patchBot(bot.id, { approvalMode: "ask", autoApprove: false });
+ const relayed = await post({ threadId, sendId: OTHER_SEND, text: words, expectedActiveLeafId: store.activeLeaf(threadId), expectedApprovalMode: "ask" }, "/guarded");
+ expect(relayed.status, JSON.stringify(relayed.body)).toBe(202);
+ expect(typedWords(threadId, [relayed.body.message])).toBe("");
+ });
+
+ it("does not take a bare loopback send as a person's on a headless server, where it may be a bot's shell", async () => {
+ const { threadId, post } = await fixture(false);
+ const plain = await post({ threadId, sendId: SEND, text: words });
+ expect(plain.status, JSON.stringify(plain.body)).toBe(202);
+ expect(typedWords(threadId, [plain.body.message])).toBe("");
+ });
+});
+
describe("POST /api/bots/:id/messages with widgetAction", () => {
it("lets the server answer a press on its own card with no turn, refuses it for someone else, and reads no widget in another bot's chat", async () => {
const { store, threadId, state, post, show, sent } = await fixture();
diff --cc server/skill-command.test.ts
index 4e01995c38,ca16c17b13..f40aea8a6d
--- a/server/skill-command.test.ts
+++ b/server/skill-command.test.ts
@@@ -1,33 -1,14 +1,33 @@@
import { describe, expect, it } from "vitest";
+import { randomUUID } from "node:crypto";
import { join } from "node:path";
-import { enabledSkillFile, expandSkillCommandTurnText, installSkill, setSkillEnabled } from "./skills.ts";
+import type { AppConfig } from "./config.ts";
+import { createSkillsLibraryHost } from "./host/skills-library.ts";
+import { enabledSkillFile, installSkill, setSkillEnabled } from "./skills.ts";
+import type { BotRecord, Store } from "./store.ts";
+import { noteTypedSend, typedWords } from "./typed-sends.ts";
import { workspaceDir } from "./workspace.ts";
- import { blankCode, BUILT_IN_SLASH_COMMANDS, expandSkillCommands, findSkillCommands, offersSkillCommand, parseSkillCommand } from "../shared/skill-command.ts";
-import { BUILT_IN_SLASH_COMMANDS, offersSkillCommand, parseSkillCommand, skillMentions } from "../shared/skill-command.ts";
++import { blankCode, BUILT_IN_SLASH_COMMANDS, offersSkillCommand, parseSkillCommand, skillCalls, skillMentions } from "../shared/skill-command.ts";
const SKILL = (name: string) =>
`---\nname: ${name}\ndescription: Writes the weekly standup note.\n---\n\n# Standup\n\nSummarize {input} as three bullets.\n`;
+const host = createSkillsLibraryHost({
+ store: { bot: () => undefined, messagesFor: () => [] } as unknown as Store,
+ cfg: {} as AppConfig,
+ appendSkillRequestCard: () => ({ requestId: "", summary: "" }),
+});
+type Line = { sendId?: string; text?: string };
+const expand = (bot: string, text: string, lines?: Line[]) => host.expandSkillCommand({ id: bot } as BotRecord, "thread", text, undefined, lines);
+function typedLine(text: string, threadId = "thread"): Line {
+ const sendId = randomUUID();
+ noteTypedSend(threadId, sendId, text);
+ return { sendId, text };
+}
++const typedBy = (bot: string, text: string) => expand(bot, text, [typedLine(text)]);
+
- function botWith(name: string, enabled = true): string {
- const bot = `slash-bot-${Math.random().toString(36).slice(2, 10)}`;
+ function botWith(name: string, enabled = true, bot = `slash-bot-${Math.random().toString(36).slice(2, 10)}`): string {
const installed = installSkill(bot, "local:test", [{ path: "SKILL.md", content: SKILL(name) }]);
expect("error" in installed).toBe(false);
if (enabled) expect("error" in setSkillEnabled(bot, name, true)).toBe(false);
@@@ -57,144 -40,55 +59,123 @@@ describe("parseSkillCommand", () =>
});
});
- describe("a /name at the very start of the text", () => {
-describe("expandSkillCommandTurnText", () => {
++describe("words a person typed", () => {
it("points the engine at the enabled skill's reviewed SKILL.md", () => {
const bot = botWith("standup");
const file = join(workspaceDir(bot), "skills", "standup", "SKILL.md");
expect(enabledSkillFile(bot, "standup")).toBe(file);
- const text = expand(bot, "/standup the billing work");
- const text = expandSkillCommandTurnText(bot, "/standup the billing work");
++ const text = typedBy(bot, "/standup the billing work");
expect(text).toContain(`Read ${JSON.stringify(file)}`);
expect(text).toContain("Request: the billing work");
expect(text).toContain("{input}");
- expect(expand(bot, "/standup")).toContain("There is no further request");
- expect(expandSkillCommandTurnText(bot, "/standup")).toContain("There is no further request");
- expect(expandSkillCommandTurnText(bot, "/standup.")).toContain("There is no further request");
++ expect(typedBy(bot, "/standup")).toContain("There is no further request");
++ expect(typedBy(bot, "/standup.")).toContain("There is no further request");
+ });
+
+ it("runs a skill named later in the message with the whole message as the request", () => {
+ const bot = botWith("standup");
+ const file = join(workspaceDir(bot), "skills", "standup", "SKILL.md");
- const text = expandSkillCommandTurnText(bot, "write up the billing work with /standup please");
++ const text = typedBy(bot, "write up the billing work with /standup please");
+ expect(text).toContain(`Read ${JSON.stringify(file)}`);
+ expect(text).toContain("Request: write up the billing work with /standup please");
- expect(expandSkillCommandTurnText(bot, "first line\n/standup.")).toContain(`Read ${JSON.stringify(file)}`);
++ expect(typedBy(bot, "first line\n/standup.")).toContain(`Read ${JSON.stringify(file)}`);
+ });
+
+ it("runs every skill named in one message", () => {
+ const bot = botWith("review", true, botWith("standup"));
+ const standup = join(workspaceDir(bot), "skills", "standup", "SKILL.md");
+ const review = join(workspaceDir(bot), "skills", "review", "SKILL.md");
- const text = expandSkillCommandTurnText(bot, "/review the diff, then /standup it and /review again");
++ const text = typedBy(bot, "/review the diff, then /standup it and /review again");
+ expect(text).toContain("ran 2 of your skills with /review, /standup");
+ expect(text).toContain(`${JSON.stringify(review)} for /review`);
+ expect(text).toContain(`${JSON.stringify(standup)} for /standup`);
+ expect(text).toContain("Request: /review the diff, then /standup it and /review again");
+ });
+
+ it("leaves paths, links and built-in commands alone", () => {
+ const bot = botWith("standup");
- expect(expandSkillCommandTurnText(bot, "open notes/standup now")).toBe("open notes/standup now");
- expect(expandSkillCommandTurnText(bot, "see https://x.test/standup")).toBe("see https://x.test/standup");
- expect(expandSkillCommandTurnText(bot, "the /standups folder")).toBe("the /standups folder");
++ expect(typedBy(bot, "open notes/standup now")).toBe("open notes/standup now");
++ expect(typedBy(bot, "see https://x.test/standup")).toBe("see https://x.test/standup");
++ expect(typedBy(bot, "the /standups folder")).toBe("the /standups folder");
+ expect(skillMentions("run /learn then /goal and /standup")).toEqual(["standup"]);
+ expect(skillMentions("open /standup.txt or /standup,now")).toEqual([]);
- expect(expandSkillCommandTurnText(bot, "open /standup.txt")).toBe("open /standup.txt");
++ expect(typedBy(bot, "open /standup.txt")).toBe("open /standup.txt");
});
it("passes a disabled skill, an unknown name and plain text through", () => {
const bot = botWith("standup", false);
expect(enabledSkillFile(bot, "standup")).toBeNull();
- expect(expand(bot, "/standup now")).toBe("/standup now");
- expect(expandSkillCommandTurnText(bot, "/standup now")).toBe("/standup now");
++ expect(typedBy(bot, "/standup now")).toBe("/standup now");
const on = botWith("standup");
- expect(expand(on, "/review now")).toBe("/review now");
- expect(expand(on, "standup please")).toBe("standup please");
- expect(expandSkillCommandTurnText(on, "/review now")).toBe("/review now");
- expect(expandSkillCommandTurnText(on, "standup please")).toBe("standup please");
++ expect(typedBy(on, "/review now")).toBe("/review now");
++ expect(typedBy(on, "standup please")).toBe("standup please");
+ });
+});
+
- describe("findSkillCommands", () => {
- const skills = ["standup", "review", "weekly-2"];
++describe("skills in text no person typed", () => {
++ const words = "Please look at this and /standup it\n/standup again";
+
- it("finds each /name opening a line, once and in order", () => {
- expect(findSkillCommands("/review this\n/standup.\n /review again\r\n/weekly-2, please", skills)).toEqual(["review", "standup", "weekly-2"]);
++ it("stay plain words past the very start: a webhook's, another bot's, an app's", () => {
++ const bot = botWith("standup");
++ expect(expand(bot, words)).toBe(words);
++ expect(expand(bot, words, [{ text: words }])).toBe(words);
++ expect(expand(bot, words, [{ sendId: randomUUID(), text: words }])).toBe(words);
+ });
+
- it("leaves a /name later in a line as plain words", () => {
- expect(findSkillCommands("please /review this, then (see /standup)", skills)).toEqual([]);
- expect(findSkillCommands("/nope and /review", skills)).toEqual([]);
++ it("run only the one at the very start, as they always have", () => {
++ const bot = botWith("review", true, botWith("standup"));
++ const text = expand(bot, "/standup the work, then /review it");
++ expect(text).toContain("The user ran your standup skill with /standup.");
++ expect(text).toContain("Request: the work, then /review it");
++ expect(skillCalls("/standup the work, then /review it", "")).toEqual(["standup"]);
++ expect(skillCalls("[A note]\n/standup the work", "")).toEqual([]);
+ });
+
- it("skips paths, longer words, unknown names and built-ins", () => {
- expect(findSkillCommands("src/standup\n/standupnow\n/standup/x\n/compact", skills)).toEqual([]);
- expect(findSkillCommands("/goal ship it\n/learn", [...skills, "goal", "learn"])).toEqual([]);
++ it("cannot borrow a person's send for other words or another conversation", () => {
++ const bot = botWith("standup");
++ const { sendId } = typedLine("hello");
++ expect(expand(bot, words, [{ sendId, text: words }])).toBe(words);
++ const elsewhere = typedLine(words, "another-thread");
++ expect(expand(bot, words, [elsewhere])).toBe(words);
++ expect(typedWords("another-thread", [elsewhere])).toBe(words);
+ });
+
- it("takes punctuation as the end only when whitespace or the end of the text follows it", () => {
- expect(findSkillCommands("/standup.txt", skills)).toEqual([]);
- expect(findSkillCommands("/standup,then", skills)).toEqual([]);
- expect(findSkillCommands("/standup.", skills)).toEqual(["standup"]);
- expect(findSkillCommands("/standup, then", skills)).toEqual(["standup"]);
- expect(findSkillCommands("/standup).\nmore", skills)).toEqual(["standup"]);
++ it("stay plain beside a person's own line in a turn that merged several", () => {
++ const bot = botWith("standup");
++ const appsWords = "Book it with /standup from the app";
++ expect(expand(bot, `hello\n\n${appsWords}`, [typedLine("hello"), { sendId: randomUUID(), text: appsWords }])).toBe(`hello\n\n${appsWords}`);
+ });
++});
+
++describe("skillMentions and code", () => {
+ it("never counts what is inside code", () => {
- expect(findSkillCommands("```\n/standup\n```", skills)).toEqual([]);
- expect(findSkillCommands("~~~sh\n/standup\n~~~", skills)).toEqual([]);
- expect(findSkillCommands("````\n```\n/standup\n```\n/review\n````", skills)).toEqual([]);
- expect(findSkillCommands("look\n```\n/standup never closed", skills)).toEqual([]);
- expect(findSkillCommands("`span that\n/standup\nruns on`", skills)).toEqual([]);
- expect(findSkillCommands(" /standup\n\t/review", skills)).toEqual([]);
++ expect(skillMentions("```\n/standup\n```")).toEqual([]);
++ expect(skillMentions("~~~sh\nrun /standup\n~~~")).toEqual([]);
++ expect(skillMentions("````\n```\n/standup\n```\n/review\n````")).toEqual([]);
++ expect(skillMentions("look\n```\n/standup never closed")).toEqual([]);
++ expect(skillMentions("use `a /standup b` here")).toEqual([]);
++ expect(skillMentions("`span that\n/standup\nruns on`")).toEqual([]);
++ expect(skillMentions(" /standup\n\t/review")).toEqual([]);
+ });
+
- it("counts a line after the code has closed, and a stray backtick hides nothing", () => {
- expect(findSkillCommands("```\n/standup\n```\n/review", skills)).toEqual(["review"]);
- expect(findSkillCommands("~~~\n```\n~~~\n/review", skills)).toEqual(["review"]);
- expect(findSkillCommands("```inline``` is not a fence\n/review", skills)).toEqual(["review"]);
- expect(findSkillCommands("it's `odd\n\n/review\n\nand `odd", skills)).toEqual(["review"]);
++ it("counts words after the code has closed, and a stray backtick hides nothing", () => {
++ expect(skillMentions("```\n/standup\n```\nthen /review")).toEqual(["review"]);
++ expect(skillMentions("~~~\n```\n~~~\n/review")).toEqual(["review"]);
++ expect(skillMentions("```inline``` is not a fence, /review")).toEqual(["review"]);
++ expect(skillMentions("it's `odd\n\n/review\n\nand `odd")).toEqual(["review"]);
+ });
+
+ it("keeps every offset when it blanks code", () => {
+ const text = "a `b` c\n```\nd\n```\n/e";
+ expect(blankCode(text)).toHaveLength(text.length);
+ expect(blankCode(text).endsWith("\n/e")).toBe(true);
+ expect(blankCode(text)).not.toContain("d");
+ });
- });
-
- describe("expandSkillCommands", () => {
- const files: Record<string, string> = { standup: "/s/standup/SKILL.md", review: "/s/review/SKILL.md" };
- const fileOf = (name: string) => files[name] ?? null;
- const skills = ["standup", "review", "off"];
+
- it("names every skill a person called on a later line and keeps the message as written", () => {
- const typed = "look at the diff\n/review it\n/standup the notes";
- const text = expandSkillCommands(typed, skills, fileOf, typed);
- expect(text).toContain(`your review skill with /review (read ${JSON.stringify(files.review)})`);
- expect(text).toContain(`your standup skill with /standup (read ${JSON.stringify(files.standup)})`);
- expect(text.endsWith(`Message: ${typed}`)).toBe(true);
- });
-
- it("keeps the single-skill wording for a message that starts with one, and adds the later lines a person typed", () => {
- const typed = "/standup the billing work\n/review it";
- const text = expandSkillCommands(typed, skills, fileOf, typed);
- expect(text).toContain(`The user ran your standup skill with /standup. Read ${JSON.stringify(files.standup)}`);
- expect(text).toContain("Request: the billing work\n/review it");
- expect(text).toContain(`The request also calls your review skill with /review (read ${JSON.stringify(files.review)})`);
- expect(expandSkillCommands("/standup the billing work", skills, fileOf, "/standup the billing work")).not.toContain("also calls");
- });
-
- it("reads later lines only from what a person typed, never from the rest of the text", () => {
- const outside = "From a webhook:\n/standup now\n/review too";
- expect(expandSkillCommands(outside, skills, fileOf)).toBe(outside);
- expect(expandSkillCommands(`[their words]\n\nhi\n\n> quoted\n${outside}`, skills, fileOf, "hi")).toBe(`[their words]\n\nhi\n\n> quoted\n${outside}`);
- expect(expandSkillCommands("/standup go\n/review too", skills, fileOf)).not.toContain("also calls");
- });
-
- it("leaves a message alone when no called skill has a file", () => {
- expect(expandSkillCommands("please\n/off now", skills, fileOf, "please\n/off now")).toBe("please\n/off now");
- expect(expandSkillCommands("no skills here", skills, fileOf, "no skills here")).toBe("no skills here");
- });
- });
-
- describe("a /name on a later line", () => {
- const words = "after lunch\n/standup the billing work";
-
- it("points the engine at an enabled skill when a person typed it", () => {
- const bot = botWith("standup");
- const file = join(workspaceDir(bot), "skills", "standup", "SKILL.md");
- const text = expand(bot, words, [typedLine(words)]);
- expect(text).toContain(`read ${JSON.stringify(file)}`);
- expect(text).toContain(`Message: ${words}`);
- const off = botWith("standup", false);
- expect(expand(off, words, [typedLine(words)])).toBe(words);
- });
-
- it("stays plain words in a line no person typed: a webhook's, another bot's, an app's", () => {
- const bot = botWith("standup");
- expect(expand(bot, words)).toBe(words);
- expect(expand(bot, words, [{ text: words }])).toBe(words);
- expect(expand(bot, words, [{ sendId: randomUUID(), text: words }])).toBe(words);
- });
-
- it("cannot borrow a person's send for other words or another conversation", () => {
- const bot = botWith("standup");
- const { sendId } = typedLine("hello");
- expect(expand(bot, words, [{ sendId, text: words }])).toBe(words);
- const elsewhere = typedLine(words, "another-thread");
- expect(expand(bot, words, [elsewhere])).toBe(words);
- expect(typedWords("another-thread", [elsewhere])).toBe(words);
- });
-
- it("reads only the typed lines of a turn that merged several", () => {
- const bot = botWith("standup");
- const appsWords = "Book it\n/standup from the app";
- expect(expand(bot, `hello\n\n${appsWords}`, [typedLine("hello"), { sendId: randomUUID(), text: appsWords }])).toBe(`hello\n\n${appsWords}`);
++ it("reads a long message of odd backtick runs quickly", () => {
++ const text = `${Array.from({ length: 2000 }, (_, index) => "`".repeat(index + 1)).join(" ")} /standup`;
++ const started = Date.now();
++ expect(skillMentions(text)).toEqual(["standup"]);
++ expect(Date.now() - started).toBeLessThan(2000);
});
});
diff --cc server/skill-commands.e2e.test.ts
index 833357eb9b,0000000000..96f2cc292e
mode 100644,000000..100644
--- a/server/skill-commands.e2e.test.ts
+++ b/server/skill-commands.e2e.test.ts
@@@ -1,107 -1,0 +1,123 @@@
- // A skill past the very start of a message runs only from a person's own line. Everything else reaches the engine through
++// A skill past the very start of a message runs only from words a person typed. Everything else reaches the engine through
+// the same turn, so this drives the real server and reads what the engine was handed.
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+
+import { launchVerificationServer } from "../scripts/control-omb.ts";
+import { removeTempDir } from "./testing/cleanup.ts";
+import { hostTimeout } from "./testing/host-timeout.ts";
+
- const CALLED = /your standup skill/;
++const CALLED = /The user ran/;
+
- it("calls a skill from a later line a person typed, never from a webhook, another bot or a bot's own shell", async () => {
++it("calls a skill mid-message from what a person typed, never from a webhook, another bot, an app or a bot's own shell", async () => {
+ const gates = mkdtempSync(join(tmpdir(), "omb-skill-commands-"));
+ const gate = join(gates, "finish");
+ const fixture = await launchVerificationServer({ FAKE_CLAUDE_MODE: "slow", FAKE_CLAUDE_SLOW_FINISH_GATE: gate });
+ const base = fixture.info.url;
+ const api = async (method: string, path: string, body?: unknown, token?: string) => {
+ const response = await fetch(base + path, {
+ method, headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ const result = await response.json() as any;
+ expect(response.status, `${method} ${path}: ${JSON.stringify(result).slice(0, 400)}`).toBeLessThan(300);
+ return result;
+ };
+ const dump = (): any => { try { return JSON.parse(readFileSync(fixture.fixtureDumpPath, "utf8")); } catch { return {}; } };
+ const prompt = (): string => {
+ const content = dump().prompt?.message?.content;
+ return Array.isArray(content) ? content.map((block: { text?: string }) => block.text ?? "").join("\n") : String(content ?? "");
+ };
+ const reached = (marker: string) => expect.poll(prompt, { timeout: hostTimeout(30_000) }).toContain(marker);
+ const quiet = () => expect.poll(async () => (await api("GET", "/api/bots?messages=0")).bots.some((bot: { busy?: boolean }) => bot.busy), { timeout: hostTimeout(30_000) }).toBe(false);
+ let sends = 0;
+ const sendId = () => `skill-e2e-send-${String(++sends).padStart(10, "0")}`;
+ try {
- const home = join(fixture.info.dataDir, "task-workspaces", ".claude", "skills", "standup");
- mkdirSync(home, { recursive: true });
- writeFileSync(join(home, "SKILL.md"), "---\nname: standup\ndescription: Writes the standup.\n---\n\nSummarize {input}.\n");
++ for (const name of ["standup", "review"]) {
++ const home = join(fixture.info.dataDir, "task-workspaces", ".claude", "skills", name);
++ mkdirSync(home, { recursive: true });
++ writeFileSync(join(home, "SKILL.md"), `---\nname: ${name}\ndescription: Writes the ${name}.\n---\n\nSummarize {input}.\n`);
++ }
+ const opened = await api("POST", "/api/auth/pairing", { label: "Ada's phone", scopes: ["client"] });
+ const person: string = (await api("POST", "/api/auth/pair", { code: opened.code, label: "Ada's phone" })).token;
+ const asker = (await api("POST", "/api/bots", { name: "Asker" })).bot;
+ const scout = (await api("POST", "/api/bots", { name: "Scout" })).bot;
+ const say = (text: string, token?: string, extra: Record<string, unknown> = {}) =>
+ api("POST", `/api/bots/${scout.id}/messages`, { threadId: scout.threadId, sendId: sendId(), text, ...extra }, token);
+
- // Another bot's words, at the very start and on a later line, while its own turn holds a live capability.
++ // Another bot's words, while its own turn holds a live capability.
+ await api("POST", `/api/bots/${asker.id}/messages`, { threadId: asker.threadId, sendId: sendId(), text: "asker-start" });
+ await reached("asker-start");
+ const comms: string = dump().mcpConfig.mcpServers.agents.env.OMB_COMMS_TOKEN;
- await api("POST", "/api/internal/coordinate-bots", { botIds: [scout.id], reply: "none", message: "/standup peer-marker\n/standup again" }, comms);
++ const page = await api("POST", "/api/internal/options-card", { tool: "show_html", html: "<p>Pick a slot</p>", title: "Booking" }, comms);
++ await api("POST", "/api/internal/coordinate-bots", { botIds: [scout.id], reply: "none", message: "/standup peer-marker please /standup now\n/standup again" }, comms);
+ await reached("peer-marker");
++ expect(prompt()).toContain(" /standup now");
+ expect(prompt()).toMatch(/^\/standup again/m);
+ expect(prompt()).not.toMatch(CALLED);
+ writeFileSync(gate, "finish");
+ await quiet();
+
- // A webhook's payload, and the automation's own prompt, on a later line.
- const hook = await api("POST", "/api/webhooks", { name: "Inbox", prompt: "Handle the event.\n/standup the event", botId: scout.id });
- const delivered = await fetch(hook.credential.url, { method: "POST", headers: { "content-type": "text/plain" }, body: "webhook-marker\n/standup now" });
++ // An app's words, sent from a paired session: the person pressed something, they did not write this.
++ await api("POST", `/api/bots/${asker.id}/messages`, { threadId: asker.threadId, sendId: sendId(), appMessage: { messageId: page.messageId, text: "app-marker please /standup now" } }, person);
++ await reached("app-marker");
++ expect(prompt()).toContain(" /standup now");
++ expect(prompt()).not.toMatch(CALLED);
++ await quiet();
++
++ // A webhook's payload, and the automation's own prompt.
++ const hook = await api("POST", "/api/webhooks", { name: "Inbox", prompt: "Handle the event with /standup the event.\n/standup too", botId: scout.id });
++ const delivered = await fetch(hook.credential.url, { method: "POST", headers: { "content-type": "text/plain" }, body: "webhook-marker please /standup now" });
+ expect(delivered.status).toBe(202);
+ await reached("webhook-marker");
- expect(prompt()).toMatch(/^\/standup the event/m);
++ expect(prompt()).toContain(" /standup now");
++ expect(prompt()).toMatch(/^\/standup too/m);
+ expect(prompt()).not.toMatch(CALLED);
+ await quiet();
+
+ // Loopback with no session, the way a bot's own shell reaches this route on a headless server.
- await say("shell-marker\n/standup now");
++ await say("shell-marker please /standup now", undefined);
+ await reached("shell-marker");
+ expect(prompt()).not.toMatch(CALLED);
+ await quiet();
+
+ // The person, from a paired session.
- await say("typed-marker\n/standup the billing work", person);
- await reached("typed-marker");
- expect(prompt()).toMatch(/The user called your standup skill with \/standup \(read "[^"]*SKILL\.md"\)/);
++ await say("midline-marker please /standup the billing work", person);
++ await reached("midline-marker");
++ expect(prompt()).toMatch(/The user ran your standup skill with \/standup\. Read "[^"]*SKILL\.md"/);
++ await quiet();
++ await say("several-marker: /standup then /review", person);
++ await reached("several-marker");
++ expect(prompt()).toContain("ran 2 of your skills with /standup, /review");
+ await quiet();
+ await say("/standup start-marker", person);
+ await reached("start-marker");
+ expect(prompt()).toMatch(/The user ran your standup skill with \/standup/);
+ await quiet();
+ for (const [marker, text] of [
- ["midline-marker", "Please /standup midline-marker"],
+ ["fence-marker", "fence-marker\n```\n/standup\n```"],
- ["dot-marker", "dot-marker\n/standup.txt is the file"],
++ ["inline-marker", "inline-marker `a /standup b`"],
++ ["dot-marker", "dot-marker /standup.txt is the file"],
+ ] as const) {
+ await say(text, person);
+ await reached(marker);
+ expect(prompt(), text).not.toMatch(CALLED);
+ await quiet();
+ }
+
- // Still the person's line after it waited its turn in the queue.
++ // Still the person's words after they waited their turn in the queue.
+ rmSync(gate);
+ await say("first-marker", person);
+ await reached("first-marker");
- expect((await say("queued-marker\n/standup the rest", person, { followUp: "queue" })).queued).toBe(true);
++ expect((await say("queued-marker please /standup the rest", person, { followUp: "queue" })).queued).toBe(true);
+ writeFileSync(gate, "finish");
+ await reached("queued-marker");
- expect(prompt()).toMatch(/The user called your standup skill/);
++ expect(prompt()).toMatch(CALLED);
+ await quiet();
+ } finally {
+ await fixture.close();
+ await removeTempDir(gates);
+ }
+}, hostTimeout(180_000));
diff --cc server/skills.ts
index 5fbc24413b,0136ae265d..bd896d9511
--- a/server/skills.ts
+++ b/server/skills.ts
@@@ -1298,12 -1299,20 +1298,16 @@@ export function skillsSystemPrompt(botI
}
export function enabledSkillFile(botId: string, name: string, assignedLibrary?: readonly string[]): string | null {
- const skill = resolveBotSkills(botId, assignedLibrary).find((entry) => entry.name === name && entry.enabled);
- if (!skill) return null;
- const entry = readManifest(botId)[name];
- return entry ? join(skillTarget(workspaceDir(botId), name, entry), "SKILL.md") : librarySkillFilePath(name);
+ return enabledSkillFiles(botId, [name], assignedLibrary).get(name) ?? null;
+ }
+
+ /** SKILL.md of each named skill that is on for the bot. */
+ export function enabledSkillFiles(botId: string, names: readonly string[], assignedLibrary?: readonly string[]): Map<string, string> {
+ if (!names.length) return new Map();
+ const on = new Set(resolveBotSkills(botId, assignedLibrary).filter((skill) => skill.enabled).map((skill) => skill.name)), manifest = readManifest(botId);
+ return new Map(names.filter((name) => on.has(name)).map((name) => [name, manifest[name] ? join(skillTarget(workspaceDir(botId), name, manifest[name]), "SKILL.md") : librarySkillFilePath(name)] as const));
}
-export function expandSkillCommandTurnText(botId: string, text: string, assignedLibrary?: readonly string[]): string {
- return skillCommandTurnText(text, enabledSkillFiles(botId, skillMentions(text), assignedLibrary));
-}
-
export function resolveBotSkills(botId: string, assignedLibrary: readonly string[] | undefined): SkillListing[] {
const own = listSkills(botId);
if (assignedLibrary === undefined) return own; // the library is off: no every-bot skills either
diff --cc shared/skill-command.ts
index bbf1ea1f8d,7233dd2f62..e682820789
--- a/shared/skill-command.ts
+++ b/shared/skill-command.ts
@@@ -1,9 -1,9 +1,10 @@@
- // `/<skill-name>` runs one of the bot's enabled skills for that turn: at the very
- // start of a message, or at the start of a later line of what a person typed
- // themselves. Like /learn and /setup it is a turn-text rewrite on the server: the
- // transcript keeps the raw message, and only the text the engine reads names the
-// `/<skill-name>` at the start of a message, or after a space anywhere in it,
-// runs one of the bot's enabled skills for that turn, and one message can run
-// several. Like /learn and /setup it is a turn-text rewrite on the server: the
-// transcript keeps the person's raw message, and only the text the engine reads
-// names each skill and its SKILL.md. Shared so the composer menu and the server
-// agree on which names are commands.
++// `/<skill-name>` runs one of the bot's enabled skills for that turn, and one
++// message can run several. The very start of a turn's text can call one, whoever
++// wrote it; past that, only words a person typed themselves can, and code never
++// does. Like /learn and /setup it is a turn-text rewrite on the server: the
++// transcript keeps the raw message, and only the text the engine reads names each
+// skill and its SKILL.md. Shared so the composer menu and the server agree on which
+// names are commands.
import { isSkillName } from "./skill-md.ts";
/** Commands the app already owns. A skill with one of these names keeps
@@@ -16,10 -16,10 +17,12 @@@ export interface SkillCommand
request: string;
}
- /** `/name` or `/name request` where name is one of `skills`. Anything else,
++const LEADING_COMMAND = /^\/([a-z0-9-]+)(?:[.,;:!?)]+(?=\s|$))?(?:\s+|$)([\s\S]*)$/;
++
+ /** `/name` or `/name request` where name is one of `skills`; punctuation right after the name (`/name.`) ends it. Anything else,
* including an engine's own slash command, is ordinary text. */
export function parseSkillCommand(text: string, skills: Iterable<string>): SkillCommand | null {
- const match = /^\/([a-z0-9-]+)(?:\s+|$)([\s\S]*)$/.exec(text.trimStart());
- const match = /^\/([a-z0-9-]+)(?:[.,;:!?)]+(?=\s|$))?(?:\s+|$)([\s\S]*)$/.exec(text.trimStart());
++ const match = LEADING_COMMAND.exec(text.trimStart());
if (!match) return null;
const name = match[1]!;
if (!isSkillName(name) || BUILT_IN_SLASH_COMMANDS.includes(name)) return null;
@@@ -32,96 -32,29 +35,89 @@@ export function offersSkillCommand(name
return isSkillName(name) && !BUILT_IN_SLASH_COMMANDS.includes(name);
}
-/** Each `/name` that starts the message or follows a space, in order and once each, never a built-in. A path or link
- * such as "a/b" or "https://x/y" names nothing. */
+const hideCode = (code: string): string => code.replace(/[^\n]/g, "\0");
+const FENCE = /^ {0,3}(`{3,}|~{3,})([^\r]*)/;
+
+/** A backtick run closes at the next run of its own length in the same paragraph. Paired from the far end, so that a person's
+ * long message of odd runs cannot stall the server, which reads it on the turn path. */
+function hideInlineCode(text: string): string {
+ const tokens = [...text.matchAll(/`+|\n[ \t]*(?=\n)/g)];
+ const closers = new Map<number, number>();
+ const nextOfLength = new Map<number, number>();
+ for (let index = tokens.length - 1; index >= 0; index -= 1) {
+ const token = tokens[index]![0];
+ if (token[0] !== "`") { nextOfLength.clear(); continue; }
+ const closer = nextOfLength.get(token.length);
+ if (closer !== undefined) closers.set(index, closer);
+ nextOfLength.set(token.length, index);
+ }
+ let out = "";
+ let at = 0;
+ for (let index = 0; index < tokens.length; index += 1) {
+ const closer = closers.get(index);
+ if (closer === undefined) continue;
+ const start = tokens[index]!.index;
+ const end = tokens[closer]!.index + tokens[closer]![0].length;
+ out += text.slice(at, start) + hideCode(text.slice(start, end));
+ at = end;
+ index = closer;
+ }
+ return out + text.slice(at);
+}
+
- /** `text` with fenced blocks and inline code blanked out, every offset kept. An unclosed fence runs to the end, as it
- * renders, and inline code ends with its paragraph. */
++/** `text` with fenced blocks, indented blocks and inline code blanked out, every offset kept. An unclosed fence runs to
++ * the end, as it renders, and inline code ends with its paragraph. */
+export function blankCode(text: string): string {
+ let fence = "";
+ return hideInlineCode(text.split("\n").map((line) => {
+ const [, run = "", rest = ""] = FENCE.exec(line) ?? [];
+ if (fence) {
+ if (run[0] === fence[0] && run.length >= fence.length && !rest.trim()) fence = "";
+ return hideCode(line);
+ }
- if (!run || (run[0] === "`" && rest.includes("`"))) return line;
++ if (!run || (run[0] === "`" && rest.includes("`"))) return /^(?: {4}|\t)/.test(line) ? hideCode(line) : line;
+ fence = run;
+ return hideCode(line);
+ }).join("\n"));
+}
+
- /** A `/name` opening a line, at most three spaces in (four is an indented code block). Punctuation may end it only when
- * whitespace or the end follows, so `/standup.` is a call and `/standup.txt` is not. */
- const LINE_CALL = /^ {0,3}\/([a-z0-9-]+)(?=[.,;:!?)]*(?:\s|$))/gm;
++/** Where a typed `/name` counts: the start of the text or after a space, ended by the end, a space, or punctuation with
++ * one of those after it. */
++const SKILL_CALL = /(?:^|\s)\/([a-z0-9-]+)(?=$|\s|[.,;:!?)]+(?:$|\s))/g;
+
- /** Each of `skills` that `text` calls at the start of a line, outside code. In order, once each. */
- export function findSkillCommands(text: string, skills: Iterable<string>): string[] {
- const known = new Set([...skills].filter(offersSkillCommand));
- const found: string[] = [];
- for (const match of blankCode(text).matchAll(LINE_CALL)) {
- const name = match[1]!;
- if (known.has(name) && !found.includes(name)) found.push(name);
++/** Each `/name` in `text` outside code, in order and once each, never a built-in. A path or link such as "a/b" or
++ * "https://x/y" names nothing. */
+ export function skillMentions(text: string): string[] {
+ const found = new Set<string>();
- for (const match of text.matchAll(/(?:^|\s)\/([a-z0-9-]+)(?=$|\s|[.,;:!?)]+(?:$|\s))/g)) {
++ for (const match of blankCode(text).matchAll(SKILL_CALL)) {
+ if (offersSkillCommand(match[1]!)) found.add(match[1]!);
}
- return found;
- }
-
- /** Whether a turn could call a skill at all, checked before the skills are listed. */
- export function mayCallSkill(text: string, typed: string): boolean {
- return text.trimStart().startsWith("/") || /^ {0,3}\//m.test(typed);
+ return [...found];
}
+/**
- * The text the engine reads for a turn that calls skills with `/name`. `text` is all the engine would read, and its very
- * start can call one skill whoever wrote it, which is why every other kind of turn opens with a note saying who it is
- * from. `typed` holds only the words a person wrote themselves: the one place a later line can call a skill. Those are
- * listed with their SKILL.md and the message follows as written. `fileOf` gives a skill's SKILL.md, or null. A turn that
- * calls no skill comes back unchanged.
++ * The skills a turn calls. Security invariant: `typed` holds only words a person wrote themselves, and it is the one place
++ * past the very start of the text that can call a skill. A webhook's payload and another bot's message reach the engine
++ * after a note saying who they are from, so the start of `text` is never theirs.
+ */
- export function expandSkillCommands(text: string, skills: readonly string[], fileOf: (name: string) => string | null, typed = ""): string {
- const command = parseSkillCommand(text, skills);
- const leadFile = command ? fileOf(command.name) : null;
- const called = findSkillCommands(typed, skills)
- .filter((name) => !leadFile || name !== command?.name)
- .flatMap((name) => {
- const file = fileOf(name);
- return file ? [{ name, file }] : [];
- });
- const reads = called.map(({ name, file }) => `your ${name} skill with /${name} (read ${JSON.stringify(file)})`).join(", ");
- if (command && leadFile) {
- const lead = `The user ran your ${command.name} skill with /${command.name}. Read ${JSON.stringify(leadFile)} with your file tools and follow it for this turn.`;
- const also = called.length > 0 ? `\n\nThe request also calls ${reads}. Read each with your file tools and follow it where the request calls it.` : "";
- return command.request
- ? `${lead} Where the skill says {input}, use the request.\n\nRequest: ${command.request}${also}`
- : `${lead} There is no further request, so run it as the skill describes.`;
- }
- if (called.length === 0) return text;
- return `The user called ${reads} in their message. Read each with your file tools and follow it where the message calls it, for this turn. Where a skill says {input}, use what the message asks of it.\n\nMessage: ${text}`;
++export function skillCalls(text: string, typed: string): string[] {
++ const leading = LEADING_COMMAND.exec(text.trimStart())?.[1];
++ return [...new Set([...(leading && offersSkillCommand(leading) ? [leading] : []), ...skillMentions(typed)])];
++}
++
+ /** What the engine reads for a message that ran skills with `/name`: which SKILL.md to read and follow, then the
+ * request. `files` maps each skill the bot has to its SKILL.md; any other `/word` stays plain text. */
-export function skillCommandTurnText(text: string, files: ReadonlyMap<string, string>): string {
- const names = skillMentions(text).filter((name) => files.has(name));
++export function skillCommandTurnText(text: string, files: ReadonlyMap<string, string>, typed = ""): string {
++ const names = skillCalls(text, typed).filter((name) => files.has(name));
+ if (!names.length) return text;
+ const read = (name: string) => JSON.stringify(files.get(name));
+ const lead = names.length === 1
+ ? `The user ran your ${names[0]} skill with /${names[0]}. Read ${read(names[0]!)} with your file tools and follow it for this turn.`
+ : `The user ran ${names.length} of your skills with ${names.map((name) => `/${name}`).join(", ")}. Read ` +
+ `${names.map((name) => `${read(name)} for /${name}`).join(", ")} with your file tools and follow each for this turn.`;
+ const leading = names.length === 1 ? parseSkillCommand(text, names) : null;
+ const request = leading ? leading.request : text.trim();
+ return request
+ ? `${lead} Where ${names.length === 1 ? "the" : "a"} skill says {input}, use the request.\n\nRequest: ${request}`
+ : `${lead} There is no further request, so run it as the skill describes.`;
}
diff --cc src/lib/composer-commands.test.ts
index 67e0d44128,eb11265751..74710c974e
--- a/src/lib/composer-commands.test.ts
+++ b/src/lib/composer-commands.test.ts
@@@ -18,35 -16,17 +16,23 @@@ describe("composer slash commands", ()
expect(composerSlashTrigger("/goal write", 11)).toBeNull();
});
- it("opens skill search for a token later in the message, after a space or a line break", () => {
- expect(composerSlashTrigger("hello /go", 9)).toEqual({ query: "go", start: 6, end: 9, atStart: false });
- expect(composerSlashTrigger("/standup billing\n/rev", 21)).toEqual({ query: "rev", start: 17, end: 21, atStart: false });
- expect(composerSlashTrigger("hello /go there", 9)).toEqual({ query: "go", start: 6, end: 9, atStart: false });
- });
-
- it("does not open inside a path, a link or a finished word", () => {
- expect(composerSlashTrigger("src/standup", 11)).toBeNull();
- expect(composerSlashTrigger("see https://example.com/a", 25)).toBeNull();
- expect(composerSlashTrigger("hello /go ", 10)).toBeNull();
+ it("opens command search for a slash token later in the message", () => {
+ expect(composerSlashTrigger("hello /go", 9)).toEqual({ query: "go", start: 6, end: 9 });
+ expect(composerSlashTrigger("first line\n/", 12)).toEqual({ query: "", start: 11, end: 12 });
+ expect(composerSlashTrigger("use /stand later", 10)).toEqual({ query: "stand", start: 4, end: 10 });
+ expect(composerSlashTrigger("a/b", 3)).toBeNull();
+ expect(composerSlashTrigger("see http://x/", 13)).toBeNull();
+ expect(
+ replaceComposerSlashTrigger("use /stand later", { query: "stand", start: 4, end: 10 }, "/standup "),
+ ).toEqual({ text: "use /standup later", caret: 13 });
});
+ it("does not open inside code, and opens again after it", () => {
+ expect(composerSlashTrigger("```\n/st", 7)).toBeNull();
+ expect(composerSlashTrigger("`a /st` b", 6)).toBeNull();
- expect(composerSlashTrigger("```\nx\n```\n/st", 13)).toEqual({ query: "st", start: 10, end: 13, atStart: false });
- });
-
- it("moves a skill picked later in a line onto a line of its own, where the server reads it", () => {
- const pick = (text: string, start: number, end: number) => replaceComposerSlashTrigger(text, { query: "", start, end }, "/standup ");
- expect(pick("hello /go", 6, 9)).toEqual({ text: "hello\n/standup ", caret: 15 });
- expect(pick("hello /go there", 6, 9)).toEqual({ text: "hello\n/standup there", caret: 15 });
- expect(findSkillCommands(pick("hello /go there", 6, 9).text, ["standup"])).toEqual(["standup"]);
- expect(pick("hello\n/go", 6, 9)).toEqual({ text: "hello\n/standup ", caret: 15 });
- expect(pick(" /go", 2, 5)).toEqual({ text: " /standup ", caret: 11 });
- expect(pick(" /go", 5, 8)).toEqual({ text: "/standup ", caret: 9 });
- expect(replaceComposerSlashTrigger("hello /go", { query: "go", start: 6, end: 9 }, "")).toEqual({ text: "hello ", caret: 6 });
++ expect(composerSlashTrigger("```\nx\n```\n/st", 13)).toEqual({ query: "st", start: 10, end: 13 });
+ });
+
it("replaces the active token without losing text after the caret", () => {
expect(
replaceComposerSlashTrigger("/go later", { query: "go", start: 0, end: 3 }, ""),
diff --cc src/lib/composer-commands.ts
index e918fcea8d,cac267b67f..f993d05f1f
--- a/src/lib/composer-commands.ts
+++ b/src/lib/composer-commands.ts
@@@ -33,13 -32,10 +32,11 @@@ export interface ComposerSlashTrigger
export function composerSlashTrigger(text: string, caretInput: number): ComposerSlashTrigger | null {
const caret = Math.max(0, Math.min(text.length, Math.floor(caretInput)));
const prefix = text.slice(0, caret);
- const match = /(^|\s)\/([a-z0-9-]*)$/i.exec(prefix);
+ const match = /(?:^|\s)\/([a-z0-9-]*)$/i.exec(prefix);
if (!match) return null;
- const start = match.index + (match[1] ?? "").length;
- if (blankCode(text)[start] !== "/") return null;
- return { query: match[2] ?? "", start, end: caret, atStart: prefix.slice(0, start).trim() === "" };
+ const query = match[1] ?? "";
- return { query, start: caret - query.length - 1, end: caret };
++ const start = caret - query.length - 1;
++ return blankCode(text)[start] === "/" ? { query, start, end: caret } : null;
}
export function goalTextFromComposer(text: string): string | null {