Skip to content

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

fix(skills): /name runs only from a person's own line, at the start of a line

milind-sonid7c463bdb30c
diff --git a/server/host/skills-library.ts b/server/host/skills-library.ts
index ed6f06ac32..1b33334ffb 100644
--- a/server/host/skills-library.ts
+++ b/server/host/skills-library.ts
@@ -7,7 +7,7 @@ import { DATA_DIR, type AppConfig } from "../config.ts";
import { appendDecision } from "../decision-log.ts";
import { UNDO_STALE, type DirectApply } from "../direct-apply.ts";
import {
- expandImportedSkillCommand, importedSkillListings, importedSkillsFor, importedSkillsPrompt, nativeSkillFolders, readImportedSkillFile, readImportedSkills,
+ importedSkillListings, importedSkillsFor, importedSkillsPrompt, nativeSkillFolders, readImportedSkillFile, readImportedSkills,
type ImportedSkillView, type SkillTurnEngine,
} from "../imported-skills.ts";
import { nativeSkillListing, nativeSkills, readNativeSkillFile } from "../native-skills.ts";
@@ -24,7 +24,9 @@ import {
updateSharedLearnedSkill,
type ShareBot,
} from "../skill-share.ts";
-import { expandSkillCommandTurnText, listSkills, readSkillFile, resolveBotSkills, skillsSystemPrompt, type SkillListing } from "../skills.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 type { BotRecord, Message, Store } from "../store.ts";
import { claudeUserSkillsEnabled } from "../turn-settings.ts";
import { TASK_WORKSPACES_DIR } from "../workspace.ts";
@@ -253,17 +255,18 @@ export function createSkillsLibraryHost(deps: SkillsLibraryHostDeps) {
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. */
- expandSkillCommand(bot: BotRecord, threadId: string, text: string, instance?: TurnInstance): string {
+ /** `/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. */
+ 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 assigned = skillsLibraryEnabled(cfg) ? liveAssigned(bot) : undefined;
- const own = expandSkillCommandTurnText(bot.id, text, assigned);
- if (own !== text || !text.trimStart().startsWith("/")) return own;
- const imported = expandImportedSkillCommand(text, importsFor(bot, assigned, instance));
- if (imported !== text) return imported;
+ 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([...resolveBotSkills(bot.id, assigned), ...importedSkillListings(bot.id, new Set())]
- .filter((skill) => !skill.enabled).map((skill) => skill.name));
- return expandImportedSkillCommand(text, nativesFor(bot, threadId, instance).filter((skill) => !switched.has(skill.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);
},
shareNote(bot: BotRecord, threadId: string, enabled: boolean): TurnShareNote {
diff --git a/server/imported-skills.test.ts b/server/imported-skills.test.ts
index 0a3c08ab53..3f76340493 100644
--- a/server/imported-skills.test.ts
+++ b/server/imported-skills.test.ts
@@ -6,12 +6,14 @@ import { afterEach, describe, expect, it } from "vitest";
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 { ensureTaskWorkspaceWithSkills } from "./skill-task-links.ts";
import { installSkill, setSkillEnabled } from "./skills.ts";
import type { BotRecord, Store } from "./store.ts";
+import { noteTypedSend } from "./typed-sends.ts";
import { ensureTaskWorkspace } from "./workspace.ts";
// HOME and the data folder are this test file's own temporary ones (server/testing/setup.ts).
@@ -58,8 +60,9 @@ describe("skills brought in from this computer", () => {
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"))}.`);
- 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 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");
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"));
@@ -185,5 +188,13 @@ describe("skills brought in from this computer", () => {
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";
+ 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);
});
});
diff --git a/server/imported-skills.ts b/server/imported-skills.ts
index 38c46b535d..12d28e9084 100644
--- a/server/imported-skills.ts
+++ b/server/imported-skills.ts
@@ -14,7 +14,6 @@ import { homedir } from "node:os";
import { dirname, isAbsolute, join, resolve } from "node:path";
import { z } from "zod";
-import { expandSkillCommands, mayCallSkill } from "../shared/skill-command.ts";
import { isSkillName } from "../shared/skill-md.ts";
import { writeFileAtomic } from "./atomic.ts";
import { DATA_DIR } from "./config.ts";
@@ -408,12 +407,6 @@ export function importedSkillsPrompt(skills: readonly ImportedSkillView[]): stri
return block(lines, skills.length - lines.length);
}
-/** `/name` for an imported skill, the way a bot's own skill command reads. */
-export function expandImportedSkillCommand(text: string, skills: readonly ImportedSkillView[]): string {
- if (!mayCallSkill(text)) return text;
- return expandSkillCommands(text, skills.map((skill) => skill.name), (name) => skills.find((skill) => skill.name === name)?.file ?? null);
-}
-
const NATIVE_SKILL_DIRS = [".claude/skills", ".agents/skills", ".grok/skills"];
/** Each level a real folder, never followed through a link. */
diff --git a/server/index.ts b/server/index.ts
index 2f9d2519f7..96badfe4ef 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -7964,7 +7964,7 @@ async function beginTurn(
const plannedConfig = sessionConfig(bot.soul);
const skillAuthoring = skillAuthoringEnabled(cfg) && agentsMounted;
const skillCommandText = supportsWorkspaceFiles(instance.driverKind)
- ? skillsHost.expandSkillCommand(bot, threadId, providerText, instance)
+ ? skillsHost.expandSkillCommand(bot, threadId, providerText, instance, personLine ? activeMessages.filter((line) => skipTranscript.has(line.id)) : [])
: providerText;
const setupText = agentsMounted ? expandSetupTurnText(skillCommandText) : skillCommandText;
const userTurnText = (opts?.app?.context ?? "") + (opts?.cardContinuation ? "" : routineRunNote(threadId, opts?.automationSource)) + labelledLine(personLine && !opts?.excludeMessageIds ? userMessage : {}, withReactionNotes(promptWithReply(
diff --git a/server/native-skills.test.ts b/server/native-skills.test.ts
index eb0b23ccf4..9e2d0f57fc 100644
--- a/server/native-skills.test.ts
+++ b/server/native-skills.test.ts
@@ -8,6 +8,7 @@ import { createSkillsLibraryHost } from "./host/skills-library.ts";
import { skillExport } from "./skill-export.ts";
import { installSkill, setSkillEnabled } from "./skills.ts";
import type { BotRecord, Store } from "./store.ts";
+import { noteTypedSend } from "./typed-sends.ts";
import { TASK_WORKSPACES_DIR } from "./workspace.ts";
// HOME and the data folder are this test file's own temporary ones (server/testing/setup.ts).
@@ -69,6 +70,25 @@ describe("skills the engine loads by itself", () => {
expect(host.expandSkillCommand(bot, "main", "/mine go")).toContain(JSON.stringify(join("workspaces", bot.id, "skills", "mine")).slice(1, -1));
});
+ it("run from a later line 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");
+ });
+
it("stay out of a bot or team package, which carries only the bot's own, library and imported skills", () => {
const { host, bot } = hostFor("claudeAgent", { cfg: { features: { claudeUserSkills: true } } as AppConfig });
plant(USER_SKILLS, "personal-notes");
diff --git a/server/routes/bot-messages-apps.test.ts b/server/routes/bot-messages-apps.test.ts
index 622e3f4e91..44ceb686b3 100644
--- a/server/routes/bot-messages-apps.test.ts
+++ b/server/routes/bot-messages-apps.test.ts
@@ -15,6 +15,7 @@ import type { RequestAuth } from "../request-auth.ts";
import { acceptedSendMatch, sendFingerprint, SendSequencer } from "../send-idempotency.ts";
import { _queuedCount, drainSteeredMessages, queuedSteeredMessage, queueSteeredMessage } from "../steer-queue.ts";
import { Store, type Message } from "../store.ts";
+import { typedWords } from "../typed-sends.ts";
import { createBotMessageRoutes, type BotMessageRouteDeps } from "./bot-messages.ts";
import { dispatchRoutes } from "./table.ts";
@@ -139,6 +140,7 @@ describe("POST /api/bots/:id/messages with appMessage", () => {
expect(answer.status, JSON.stringify(answer.body)).toBe(202);
expect(answer.body.message).toMatchObject({ role: "user", text: "Book the 3pm slot", replyToId: appId, sendId: id, fromApp: { messageId: appId, title: "Booking" } });
expect(sent()).toHaveLength(1);
+ expect(typedWords(threadId, [answer.body.message])).toBe("");
expect(state.accepted[0]).toMatchObject({ text: "Book the 3pm slot", replyTo: { id: appId, appMessage: { title: "Booking", origin: "a page you made with show_html" } }, app: { fromApp: { messageId: appId, title: "Booking" } } });
expect(state.accepted[0]!.dataContext).toBeUndefined();
// The stored row is not marked; only the copy the prompt is composed from is.
diff --git a/server/routes/bot-messages.test.ts b/server/routes/bot-messages.test.ts
index 49836a12e6..5ecd62818b 100644
--- a/server/routes/bot-messages.test.ts
+++ b/server/routes/bot-messages.test.ts
@@ -15,6 +15,7 @@ import type { RequestAuth } from "../request-auth.ts";
import { acceptedSendMatch, sendFingerprint, SendSequencer } from "../send-idempotency.ts";
import { _queuedCount, drainSteeredMessages, queuedSteeredMessage, queueSteeredMessage } from "../steer-queue.ts";
import { Store, type Message } from "../store.ts";
+import { typedWords } from "../typed-sends.ts";
import { createBotMessageRoutes, type BotMessageRouteDeps } from "./bot-messages.ts";
import { dispatchRoutes } from "./table.ts";
@@ -40,7 +41,7 @@ class DirectSendRefused extends Error {
type AcceptInput = Parameters<BotMessageRouteDeps["acceptDirectSend"]>[0];
-async function fixture() {
+async function fixture(desktopManaged = true) {
const store = new Store(() => sonnet);
const bot = store.createBot({ name: "Scout" });
const threadId = bot.threadId;
@@ -95,7 +96,7 @@ async function fixture() {
const deps = {
store,
routines: () => null,
- desktopManaged: true,
+ desktopManaged,
cloudHome: false,
DirectSendRefused,
acceptDirectSend: accept,
@@ -161,6 +162,34 @@ async function fixture() {
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";
+
+ 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, 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("");
+ 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 --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.ts
index 55e4290b39..f0e9d59d99 100644
--- a/server/routes/bot-messages.ts
+++ b/server/routes/bot-messages.ts
@@ -32,6 +32,7 @@ import type { BotRecord, GroupRecord, Message, Store } from "../store.ts";
import { extractSteerImages } from "../turn-images.ts";
import { followupFacts, helperFollowup, helperFollowupBody, mayFollowUp } from "../helper-followup.ts";
import type { UsageTrigger } from "../usage-ledger.ts";
+import { noteTypedSend } from "../typed-sends.ts";
import { pinnedClientThreadGuard } from "./pinned-client-thread.ts";
import { PASS, type RouteHandler } from "./table.ts";
@@ -312,13 +313,15 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler
}
: undefined;
if (phone && sendId) notePhoneSend(sendId);
+ // The bot's own shell reaches this route on a headless server (loopback is the owner), so only a
+ // paired session or the desktop capability proves a person and lifts the webhook block.
+ const personPresent = auth.kind === "session" || DESKTOP_MANAGED;
+ if (personPresent && sendId && !guarded && !press && !appSent) noteTypedSend(threadId, sendId, text);
if (pressKey) pressesInFlight.set(pressKey, sendId);
try {
const receipt = await acceptDirectSend({
botId: bot.id, threadId, text, sendId, replyTo, sender, trigger, dataContext, ...(app ? { app } : {}),
- // The bot's own shell reaches this route on a headless server (loopback is the owner), so only a
- // paired session or the desktop capability proves a person and lifts the webhook block.
- personPresent: auth.kind === "session" || DESKTOP_MANAGED, ...(followUp ? { followUp } : {}),
+ personPresent, ...(followUp ? { followUp } : {}),
}, guardedStart);
press?.settle("queueId" in receipt ? receipt.queueId : undefined);
appContext?.deliver();
diff --git a/server/skill-command.test.ts b/server/skill-command.test.ts
index bdcf372857..4e01995c38 100644
--- a/server/skill-command.test.ts
+++ b/server/skill-command.test.ts
@@ -1,13 +1,31 @@
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 { BUILT_IN_SLASH_COMMANDS, expandSkillCommands, findSkillCommands, offersSkillCommand, parseSkillCommand } from "../shared/skill-command.ts";
+import { blankCode, BUILT_IN_SLASH_COMMANDS, expandSkillCommands, findSkillCommands, offersSkillCommand, parseSkillCommand } 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 };
+}
+
function botWith(name: string, enabled = true): string {
const bot = `slash-bot-${Math.random().toString(36).slice(2, 10)}`;
const installed = installSkill(bot, "local:test", [{ path: "SKILL.md", content: SKILL(name) }]);
@@ -39,39 +57,74 @@ describe("parseSkillCommand", () => {
});
});
-describe("expandSkillCommandTurnText", () => {
+describe("a /name at the very start of the text", () => {
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 = expandSkillCommandTurnText(bot, "/standup the billing work");
+ const text = expand(bot, "/standup the billing work");
expect(text).toContain(`Read ${JSON.stringify(file)}`);
expect(text).toContain("Request: the billing work");
expect(text).toContain("{input}");
- expect(expandSkillCommandTurnText(bot, "/standup")).toContain("There is no further request");
+ expect(expand(bot, "/standup")).toContain("There is no further request");
});
it("passes a disabled skill, an unknown name and plain text through", () => {
const bot = botWith("standup", false);
expect(enabledSkillFile(bot, "standup")).toBeNull();
- expect(expandSkillCommandTurnText(bot, "/standup now")).toBe("/standup now");
+ expect(expand(bot, "/standup now")).toBe("/standup now");
const on = botWith("standup");
- expect(expandSkillCommandTurnText(on, "/review now")).toBe("/review now");
- expect(expandSkillCommandTurnText(on, "standup please")).toBe("standup please");
+ expect(expand(on, "/review now")).toBe("/review now");
+ expect(expand(on, "standup please")).toBe("standup please");
});
});
describe("findSkillCommands", () => {
const skills = ["standup", "review", "weekly-2"];
- it("finds each /name that is its own word, anywhere in the message, once and in order", () => {
- expect(findSkillCommands("please /review this, then /standup.\n/review again", skills)).toEqual(["review", "standup"]);
- expect(findSkillCommands("/weekly-2 and (see /standup)", skills)).toEqual(["weekly-2", "standup"]);
+ 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("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("skips paths, longer words, unknown names and built-ins", () => {
- expect(findSkillCommands("edit src/standup or /standupnow or /compact", skills)).toEqual([]);
- expect(findSkillCommands("/goal ship it /learn", [...skills, "goal", "learn"])).toEqual([]);
+ 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("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("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([]);
+ });
+
+ 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("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");
});
});
@@ -80,35 +133,68 @@ describe("expandSkillCommands", () => {
const fileOf = (name: string) => files[name] ?? null;
const skills = ["standup", "review", "off"];
- it("names every skill called later in a message and keeps the message as written", () => {
- const text = expandSkillCommands("look at the diff, /review it and write /standup notes", skills, fileOf);
+ 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: look at the diff, /review it and write /standup notes")).toBe(true);
+ expect(text.endsWith(`Message: ${typed}`)).toBe(true);
});
- it("keeps the single-skill wording for a message that starts with one, and adds the others it calls", () => {
- const text = expandSkillCommands("/standup the billing work, then /review it", skills, fileOf);
+ 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, then /review it");
+ 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)).not.toContain("also calls");
+ 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 /off now", skills, fileOf)).toBe("please /off now");
- expect(expandSkillCommands("no skills here", skills, fileOf)).toBe("no skills here");
+ 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("expandSkillCommandTurnText later in a message", () => {
- it("points the engine at an enabled skill called mid-sentence", () => {
+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 = expandSkillCommandTurnText(bot, "after lunch, /standup the billing work");
+ const text = expand(bot, words, [typedLine(words)]);
expect(text).toContain(`read ${JSON.stringify(file)}`);
- expect(text).toContain("Message: after lunch, /standup the billing work");
+ expect(text).toContain(`Message: ${words}`);
const off = botWith("standup", false);
- expect(expandSkillCommandTurnText(off, "after lunch, /standup")).toBe("after lunch, /standup");
+ 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}`);
});
});
diff --git a/server/skill-commands.e2e.test.ts b/server/skill-commands.e2e.test.ts
new file mode 100644
index 0000000000..833357eb9b
--- /dev/null
+++ b/server/skill-commands.e2e.test.ts
@@ -0,0 +1,107 @@
+// A skill past the very start of a message runs only from a person's own line. 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/;
+
+it("calls a skill from a later line a person typed, never from a webhook, another bot 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");
+ 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.
+ 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);
+ await reached("peer-marker");
+ 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" });
+ expect(delivered.status).toBe(202);
+ await reached("webhook-marker");
+ expect(prompt()).toMatch(/^\/standup the event/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 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 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"],
+ ] 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.
+ 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);
+ writeFileSync(gate, "finish");
+ await reached("queued-marker");
+ expect(prompt()).toMatch(/The user called your standup skill/);
+ await quiet();
+ } finally {
+ await fixture.close();
+ await removeTempDir(gates);
+ }
+}, hostTimeout(180_000));
diff --git a/server/skills.ts b/server/skills.ts
index 30ecb89e82..5fbc24413b 100644
--- a/server/skills.ts
+++ b/server/skills.ts
@@ -33,7 +33,6 @@ import {
} from "./skill-storage.ts";
import { workspaceDir } from "./workspace.ts";
import { isSkillName, parseSkillMd, scanSkillText, SKILL_FILE_MAX_BYTES, type ParsedSkill } from "../shared/skill-md.ts";
-import { expandSkillCommands, mayCallSkill } from "../shared/skill-command.ts";
export {
DESCRIPTION_MAX,
@@ -1305,12 +1304,6 @@ export function enabledSkillFile(botId: string, name: string, assignedLibrary?:
return entry ? join(skillTarget(workspaceDir(botId), name, entry), "SKILL.md") : librarySkillFilePath(name);
}
-export function expandSkillCommandTurnText(botId: string, text: string, assignedLibrary?: readonly string[]): string {
- if (!mayCallSkill(text)) return text;
- const names = resolveBotSkills(botId, assignedLibrary).filter((skill) => skill.enabled).map((skill) => skill.name);
- return expandSkillCommands(text, names, (name) => enabledSkillFile(botId, name, 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 --git a/server/typed-sends.ts b/server/typed-sends.ts
new file mode 100644
index 0000000000..cd8e75253b
--- /dev/null
+++ b/server/typed-sends.ts
@@ -0,0 +1,24 @@
+// The sends a person typed themselves, noted at the one route that can tell: a paired session or the desktop's own page,
+// and no button press, app or relay. Only these can call a skill past the start of a message, so a webhook, an app's words
+// or another bot's shell on this machine never can. Bound to the thread and the words: a bot that reads a person's sendId
+// in a transcript cannot lend it to words of its own. In memory on purpose: a queued line that outlives a restart only
+// falls back to the start-of-message rule.
+import { createHash } from "node:crypto";
+
+import { createPhoneSends } from "./phones/sends.ts";
+
+const sends = createPhoneSends();
+const proof = (threadId: string, sendId: string, text: string): string =>
+ createHash("sha256").update(JSON.stringify([threadId, sendId, text])).digest("base64");
+
+export function noteTypedSend(threadId: string, sendId: string, text: string): void {
+ sends.note(proof(threadId, sendId, text));
+}
+
+/** What the person typed themselves among a turn's own lines; empty when they typed none of them. */
+export function typedWords(threadId: string, lines: ReadonlyArray<{ sendId?: string; text?: string }>): string {
+ return lines
+ .filter((line) => line.sendId !== undefined && line.text !== undefined && sends.has(proof(threadId, line.sendId, line.text)))
+ .map((line) => line.text)
+ .join("\n\n");
+}
diff --git a/shared/skill-command.ts b/shared/skill-command.ts
index b1acc227c4..bbf1ea1f8d 100644
--- a/shared/skill-command.ts
+++ b/shared/skill-command.ts
@@ -1,8 +1,9 @@
-// `/<skill-name>` at the start of a message runs one of the bot's enabled
-// skills for that turn. Like /learn and /setup it is a turn-text rewrite on
-// the server: the transcript keeps the person's raw "/name …" message, and
-// only the text the engine reads names the 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: 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 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
@@ -31,35 +32,84 @@ export function offersSkillCommand(name: string): boolean {
return isSkillName(name) && !BUILT_IN_SLASH_COMMANDS.includes(name);
}
-/** Each `/name` in `text` that is one of `skills` and stands as its own word: at the start or after a space or
- * line break, and followed by a space, the end, or punctuation. In order, once each. A path such as `src/standup`
- * or a longer word such as `/standupnow` is not a call. */
+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. */
+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;
+ 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;
+
+/** 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 text.matchAll(/(?<=^|\s)\/([a-z0-9-]+)(?=$|\s|[.,;:!?)])/g)) {
+ for (const match of blankCode(text).matchAll(LINE_CALL)) {
const name = match[1]!;
if (known.has(name) && !found.includes(name)) found.push(name);
}
return found;
}
-/** Whether `text` has a `/` that could start a skill call, checked before the skills are listed. */
-export function mayCallSkill(text: string): boolean {
- return /(?:^|\s)\//.test(text);
+/** 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);
}
/**
- * The text the engine reads for a message that calls skills with `/name`. A message that starts with one keeps
- * the single-skill wording; skills called later in it, or anywhere in a message that starts with plain text, are
- * listed with their SKILL.md and the message follows as written. `fileOf` gives an enabled skill's SKILL.md, or
- * null. A message that calls no enabled skill comes back unchanged.
+ * 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.
*/
-export function expandSkillCommands(text: string, skills: readonly string[], fileOf: (name: string) => string | null): string {
+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(command && leadFile ? command.request : text, skills)
- .filter((name) => name !== command?.name || !leadFile)
+ const called = findSkillCommands(typed, skills)
+ .filter((name) => !leadFile || name !== command?.name)
.flatMap((name) => {
const file = fileOf(name);
return file ? [{ name, file }] : [];
diff --git a/src/components/Composer.tsx b/src/components/Composer.tsx
index dd4c8404ee..2d500b2aac 100644
--- a/src/components/Composer.tsx
+++ b/src/components/Composer.tsx
@@ -302,7 +302,6 @@ export function Composer({
const commandCandidates = useMemo(() => {
if (!slash || slash.start === dismissedSlashAt) return [];
const available: ComposerSlashCommand[] = [];
- // Later in a message only skills run: /goal, /learn and /setup are read at its start.
if (slash.atStart && !group?.dm) available.push({
kind: "command",
id: "goal",
diff --git a/src/lib/composer-commands.test.ts b/src/lib/composer-commands.test.ts
index 04d66b9fab..67e0d44128 100644
--- a/src/lib/composer-commands.test.ts
+++ b/src/lib/composer-commands.test.ts
@@ -7,6 +7,7 @@ import {
slashCommandMatches,
type ComposerSlashCommandId,
} from "./composer-commands";
+import { findSkillCommands } from "../../shared/skill-command";
import { enabledSlashSkills } from "./use-slash-skills";
describe("composer slash commands", () => {
@@ -29,6 +30,23 @@ describe("composer slash commands", () => {
expect(composerSlashTrigger("hello /go ", 10)).toBeNull();
});
+ 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 });
+ });
+
it("replaces the active token without losing text after the caret", () => {
expect(
replaceComposerSlashTrigger("/go later", { query: "go", start: 0, end: 3 }, ""),
diff --git a/src/lib/composer-commands.ts b/src/lib/composer-commands.ts
index f3afad8cbe..e918fcea8d 100644
--- a/src/lib/composer-commands.ts
+++ b/src/lib/composer-commands.ts
@@ -1,4 +1,4 @@
-import { offersSkillCommand } from "../../shared/skill-command";
+import { blankCode, offersSkillCommand } from "../../shared/skill-command";
export type ComposerSlashCommandId = "goal" | "learn" | "setup";
@@ -30,14 +30,15 @@ export interface ComposerSlashTrigger {
atStart: boolean;
}
-/** The `/word` the caret is in, at the start of the text or after a space or line break, so skills can be called
- * anywhere in a message. `atStart` is whether only spaces come before it: the built-in commands work only there. */
+/** The `/word` the caret is in, at the start of the text or after a space or line break, outside code, so a skill can be
+ * picked anywhere in a message. `atStart` is whether only spaces come before it: the built-in commands work only there. */
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);
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() === "" };
}
@@ -46,11 +47,15 @@ export function goalTextFromComposer(text: string): string | null {
return match ? (match[1] ?? "").trimStart() : null;
}
+/** A skill runs only from the start of a line, so one picked later in a line moves onto a line of its own. A pick reaches
+ * the server as plain text and nothing else travels with it, so nothing but a person's own line can pass for one. */
export function replaceComposerSlashTrigger(
text: string,
trigger: Omit<ComposerSlashTrigger, "atStart">,
replacement: string,
): { text: string; caret: number } {
- const next = `${text.slice(0, trigger.start)}${replacement}${text.slice(trigger.end)}`;
- return { text: next, caret: trigger.start + replacement.length };
+ const before = text.slice(0, trigger.start);
+ const kept = before.trimEnd();
+ const head = !replacement || /(?:^|\n) {0,3}$/.test(before) ? before : kept && `${kept}\n`;
+ return { text: `${head}${replacement}${text.slice(trigger.end)}`, caret: head.length + replacement.length };
}