All files / src/util chatCommands.ts

98.64% Statements 73/74
96.55% Branches 56/58
100% Functions 21/21
100% Lines 59/59

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227                            16x                                               16x   16x   16x           349x 349x         167x 334x                             58x 58x 21x 21x 21x 21x 21x   26x 58x 15x                             235x 171x 171x 13x 13x 11x   11x           303x 303x                                   155x 155x 155x 66x 2x   155x             16x 268x           7x 7x           190x                   363x 163x         163x 326x 639x                     4x                             51x 9x 9x 9x 8x 4x   4x                   3x 3x 3x 2x   3x 1x 1x   3x    
import type {
  ChatCommandRecord,
  ChatCommandSpec,
  ChatCommandTarget,
} from "@/objects/ChatCommand";
import { REQUIRED } from "@/util/runForm";
 
/**
 * Reading a chat command — `/<action> <kind> <target> [request]` — the way
 * svc-core does (`app/services/chat_commands.py` `parse`), against the
 * catalogue it served. The server is the authority: this only drives the
 * palette and the hint, and lets the chat show a sent command as what it is.
 */
 
export const COMMAND_PREFIX = "/";
 
/** One complete command line the palette can insert. */
export interface CommandEntry {
  spec: ChatCommandSpec;
  target: ChatCommandTarget;
  /** `/execute skill research-brief` */
  line: string;
}
 
/** A command line in the input, and the request after it. */
export interface MatchedCommand extends CommandEntry {
  request: string;
}
 
/** A command the chat sends: the token, its form's typed values (svc-core's
 *  `command_inputs`) and the free text after it. */
export interface CommandSubmission {
  entry: CommandEntry;
  inputs: Record<string, unknown>;
  request: string;
}
 
const COMMAND_RE =
  /^\/(\S+)(?:[ \t]+(\S+))?(?:[ \t]+(\S+))?(?:\s+([\s\S]*))?$/;
/** A complete command line, then the whitespace that ends it. */
const TOKEN_RE = /^\s*\/(\S+)[ \t]+(\S+)[ \t]+(\S+)(\s[\s\S]*)$/;
/** "/" then at most the action, kind and target — no request yet. */
const TYPING_RE = /^\/\S*(?:[ \t]+\S*){0,2}$/;
 
export function commandLine(
  spec: ChatCommandSpec,
  target?: ChatCommandTarget,
): string {
  const base = `${COMMAND_PREFIX}${spec.action} ${spec.kind}`;
  return target ? `${base} ${target.slug}` : base;
}
 
/** Every command line the catalogue offers, in its order. */
export function commandEntries(commands: ChatCommandSpec[]): CommandEntry[] {
  return commands.flatMap((spec) =>
    spec.targets.map((target) => ({
      spec,
      target,
      line: commandLine(spec, target),
    })),
  );
}
 
/** The command `input` runs, or null: a known action and kind, and a target
 *  the catalogue lists. Case and spacing do not matter, and the request
 *  keeps its line breaks, as on the server. */
export function matchCommand(
  input: string,
  commands: ChatCommandSpec[] | undefined,
): MatchedCommand | null {
  const text = input.trim();
  if (!commands?.length || !text.startsWith(COMMAND_PREFIX)) return null;
  const m = COMMAND_RE.exec(text);
  Iif (!m) return null;
  const [, action, kind = "", slug = "", request = ""] = m;
  const spec = commands.find(
    (c) => c.action === action.toLowerCase() && c.kind === kind.toLowerCase(),
  );
  const target = spec?.targets.find((t) => t.slug === slug.toLowerCase());
  if (!spec || !target) return null;
  return {
    spec,
    target,
    line: commandLine(spec, target),
    request: request.trim(),
  };
}
 
/** A command line the person has finished typing — followed by a space or a
 *  line break — and what follows it: the moment the chat turns the line into
 *  a token. Pasted text tokenises the same way. */
export function tokenizeCommand(
  input: string,
  commands: ChatCommandSpec[] | undefined,
): { entry: CommandEntry; request: string } | null {
  if (!commands?.length) return null;
  const m = TOKEN_RE.exec(input);
  if (!m) return null;
  const match = matchCommand(`/${m[1]} ${m[2]} ${m[3]}`, commands);
  if (!match) return null;
  const { spec, target, line } = match;
  // The whitespace that ended the line goes; the rest is kept as typed.
  return { entry: { spec, target, line }, request: m[4].slice(1) };
}
 
/** Whether a target needs the free text: one with no form fields does, and
 *  one with fields takes it as optional instructions. */
export function requestRequired(entry: CommandEntry): boolean {
  const form = entry.target.form;
  return form ? form.request === "required" : entry.spec.request_required;
}
 
/** What still stops a command from being sent, in the order a person would
 *  fix it: required fields left blank, values that cannot be read, then the
 *  free text when the target needs it. svc-core refuses each of them too. */
export interface CommandBlockers {
  missing: string[];
  invalid: Record<string, string>;
  request: boolean;
}
 
/** `errors` are `toInputs`'s for the target's form. */
export function commandBlockers(
  entry: CommandEntry,
  errors: Record<string, string>,
  request: string,
): CommandBlockers {
  const missing: string[] = [];
  const invalid: Record<string, string> = {};
  for (const [name, error] of Object.entries(errors)) {
    if (error === REQUIRED) missing.push(name);
    else invalid[name] = error;
  }
  return {
    missing,
    invalid,
    request: requestRequired(entry) && !request.trim(),
  };
}
 
export const commandReady = (blockers: CommandBlockers): boolean =>
  blockers.missing.length === 0 &&
  Object.keys(blockers.invalid).length === 0 &&
  !blockers.request;
 
/** The text a command is sent as: its line, then the free text. */
export function commandText(entry: CommandEntry, request: string): string {
  const text = request.trim();
  return text ? `${entry.line} ${text}` : entry.line;
}
 
/** Whether `input` is a command still being typed: the palette shows while
 *  it is, and closes once a target is chosen and the request begins. */
export function isTypingCommand(input: string): boolean {
  return TYPING_RE.test(input);
}
 
/** The palette's entries for `input`: the command lines containing every
 *  word typed after "/", matched against the line and the target's name —
 *  so "/brief" finds `/execute skill research-brief`. */
export function paletteEntries(
  input: string,
  commands: ChatCommandSpec[] | undefined,
): CommandEntry[] {
  if (!commands?.length || !isTypingCommand(input)) return [];
  const words = input
    .slice(COMMAND_PREFIX.length)
    .toLowerCase()
    .split(/\s+/)
    .filter(Boolean);
  return commandEntries(commands).filter((entry) => {
    const haystack = `${entry.line} ${entry.target.name}`.toLowerCase();
    return words.every((word) => haystack.includes(word));
  });
}
 
/** What a sent command's user message records, before the server has
 *  stored it (svc-core `ParsedCommand.meta()`). */
export function commandRecord(
  match: CommandEntry,
  inputs: Record<string, unknown> = {},
  request = "",
): ChatCommandRecord {
  return {
    line: match.line,
    action: match.spec.action,
    kind: match.spec.kind,
    target_id: match.target.id,
    target_name: match.target.name,
    inputs,
    request: request.trim(),
  };
}
 
/** The chat command a stored user message ran: its `meta.command`, or —
 *  stored before 24 October 2026, when a chat kept the record as the
 *  message's whole meta — the meta itself. */
export function commandOf(meta: unknown): ChatCommandRecord | undefined {
  if (!meta || typeof meta !== "object") return undefined;
  const record = meta as Record<string, unknown>;
  const nested = record.command;
  if (nested && typeof nested === "object") return nested as ChatCommandRecord;
  if (typeof record.line === "string" && typeof record.action === "string") {
    return record as unknown as ChatCommandRecord;
  }
  return undefined;
}
 
/** A refused command's message, with the lines the server suggested and
 *  what it said about each form field it refused. */
export function describeCommandError(
  message: string,
  suggestions: string[] | undefined,
  fields?: Record<string, string> | null,
): string {
  let text = message;
  const refused = Object.entries(fields ?? {});
  if (refused.length) {
    text += `\n\n${refused.map(([name, why]) => `- \`${name}\`: ${why}`).join("\n")}`;
  }
  if (suggestions?.length) {
    const lines = suggestions.map((s) => `\`${s}\``).join(", ");
    text += `\n\nDid you mean ${lines}?`;
  }
  return text;
}