chore: import ovis-composer into repo with baseline tests

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
FactorandClaude Sonnet 5.5 committed 2026-11-19 11:06:12 +01:00
1 parent edf09cf532
commit c05e252d79
21 files changed
+4312

No files matched your search

+171
View File
@@ -0,0 +1,171 @@
// attachments.js - what may be attached to a message and how it is named.
//
// Pure: no gpui-kit, no gpui-base, no herdr. The limits and the mention rules
// live here, so the view (Task 8) has one place to ask and the tests
// (tests/attachments.test.mjs) can check them in plain Node.
//
// The mention holds the path on the AGENT's machine - the path `hc put`
// printed, the file as it landed there - and not the local path of the file
// that was dropped. For a remote machine the local path does not even exist.
/** The limits the composer keeps to (the same numbers Ovis uses). */
export const LIMITS = {
fileBytes: 32 * 1024 * 1024,
filesPerAction: 100,
messageChars: 20000,
};
/** The extensions that make a file an image (the design's §13.8 list). */
const IMAGE_EXTENSIONS = new Set(["png", "jpg", "jpeg", "gif", "webp", "svg", "bmp"]);
/**
* May this file be attached?
*
* Two rules: the file may not be bigger than 32 MiB, and the composer has to
* know what it is - a file it can carry or an image it can show a thumbnail
* of. A size that could not be measured is not a size that broke the limit,
* so it passes; a size that is not a number at all is a broken file.
*
* @param {{name?:string, path?:string, bytes?:number, kind?:string}} file
* @returns {{ok:true} | {ok:false, reason:string}}
*/
export function validate(file) {
if (!file || typeof file !== "object" || Array.isArray(file)) {
return { ok: false, reason: "Nieznany plik" };
}
const bytes = file.bytes;
if (bytes !== undefined && bytes !== null && !Number.isFinite(bytes)) {
return { ok: false, reason: "Nieznany rozmiar pliku" };
}
if (Number.isFinite(bytes) && bytes > LIMITS.fileBytes) {
return { ok: false, reason: `Plik przekracza limit ${LIMITS.fileBytes / 1024 / 1024} MiB` };
}
const kind = kindOf(file);
if (kind !== "file" && kind !== "image") {
return { ok: false, reason: "Nieobsługiwany typ pliku" };
}
return { ok: true };
}
/**
* May this many files be attached in one go?
*
* One action - one drop, one send - carries at most 100 files, and every one
* of them has to pass on its own.
*
* @param {object[]} files
* @returns {{ok:true} | {ok:false, reason:string}}
*/
export function validateMany(files) {
const list = Array.isArray(files) ? files : [];
if (list.length > LIMITS.filesPerAction) {
return { ok: false, reason: `Za dużo plików (limit ${LIMITS.filesPerAction})` };
}
for (const file of list) {
const result = validate(file);
if (!result.ok) return result;
}
return { ok: true };
}
/**
* The mention of an attachment - the path as the agent sees it.
*
* @param {string} path - the path on the agent's machine
* @returns {string} the mention, or nothing when there is no path
*/
export function mention(path) {
if (typeof path !== "string") return "";
const clean = path.trim();
return clean === "" ? "" : `@${clean}`;
}
/**
* Take the mention of an attachment out of the text.
*
* Only the mention itself goes: a longer word that starts with the same
* characters (`@src/a.rsx`) is left alone. The space that separated the
* mention from the rest of the sentence goes with it, so the text does not
* keep a hole where the mention was.
*
* @param {string} text
* @param {string} path - the agent-side path, the one `mention` builds
* @returns {string}
*/
export function removeMention(text, path) {
if (typeof text !== "string") return "";
const token = mention(path);
if (token === "" || text === "") return text;
const kept = [];
let rest = text;
for (;;) {
const at = rest.indexOf(token);
if (at < 0) break;
const before = at === 0 ? "" : rest[at - 1];
const after = rest[at + token.length] ?? "";
const afterNext = rest[at + token.length + 1] ?? "";
if (!standalone(before, after, afterNext)) {
// a longer word that starts with the same characters - not our mention
kept.push(rest.slice(0, at + token.length));
rest = rest.slice(at + token.length);
continue;
}
kept.push(rest.slice(0, at));
rest = rest.slice(at + token.length).replace(/^[ \t]+/, "");
// the mention ended the line - the space before it goes too
const tail = kept[kept.length - 1];
if (/[ \t]$/.test(tail) && (rest === "" || rest.startsWith("\n"))) {
kept[kept.length - 1] = tail.replace(/[ \t]+$/, "");
}
}
kept.push(rest);
return kept.join("");
}
/**
* What the file is: what the caller says it is, or - when it says nothing -
* what the name says. Anything else than a file or an image is a type the
* composer cannot carry.
*
* @param {{name?:string, kind?:string}} file
* @returns {string}
*/
function kindOf(file) {
if (typeof file.kind === "string" && file.kind !== "") return file.kind.toLowerCase();
const name = typeof file.name === "string" ? file.name.toLowerCase() : "";
const dot = name.lastIndexOf(".");
if (dot < 0) return "file";
const extension = name.slice(dot + 1);
return IMAGE_EXTENSIONS.has(extension) ? "image" : "file";
}
/**
* Is the mention a word of its own? A word may not be glued to the mention
* on either side, and a dot that continues the path (`@src/a.rs.txt`) makes
* it a different file.
*
* @param {string} before - the character in front of the mention
* @param {string} after - the character behind the mention
* @param {string} afterNext - the character behind that one
* @returns {boolean}
*/
function standalone(before, after, afterNext) {
if (before !== "" && /[\w/\\-]/.test(before)) return false;
if (after !== "" && /[\w/\\-]/.test(after)) return false;
if (after === "." && /[\w/\\-]/.test(afterNext)) return false;
return true;
}
+367
View File
@@ -0,0 +1,367 @@
// catalog.js - where the composer's suggestions come from.
//
// The workspace is reached only through the injected `exec` (the mod's
// `herdr.exec`), so this module runs in plain Node (tests/suggest.test.mjs)
// with a fake runner. It has no clock and no storage of its own: the view
// reads the person's snippets and passes them in, and it schedules the retry
// and the debounce with the numbers exported here.
//
// Three sources for `/` (the design's §5.3): the built-in commands of the
// agent, the project's own `.claude/commands/*.md` and
// `.claude/skills/*/SKILL.md`, and the person's saved snippets. One source
// for `@`: the files git tracks in the pane's folder.
//
// A read that fails is not an empty list: the failure is reported through
// `onReadError` and the menu keeps what it knows. A caller with no handler
// gets the failure itself - nobody may mistake a broken catalog for one
// with nothing to show. An empty list without a failure means the catalog
// was read and nothing fit.
import { GROUP_BUILTIN, GROUP_PROJECT, GROUP_USER, rank } from "./suggest.js";
/**
* @typedef {import("./suggest.js").Item} Item
*
* @typedef {object} ExecResult
* @property {number} code
* @property {string} stdout
* @property {string} stderr
*
* @typedef {(command:string, args?:string[], options?:{cwd?:string}) => Promise<ExecResult>} Exec
*/
/** How long the composer waits before it asks the workspace again. */
export const DEBOUNCE_MS = 150;
/** The waits between the tries after a read failed: 2 s, 5 s, 15 s, 30 s. */
export const RETRY_DELAYS = [2000, 5000, 15000, 30000];
/** The catalog could not be read - the person may keep typing. */
export const READ_ERROR_MESSAGE =
"Nie udało się wczytać podpowiedzi. Pisz dalej, spróbujemy ponownie.";
/** The catalog was read and nothing fit the needle. */
export const NO_MATCH_MESSAGE = "Żadna komenda nie pasuje. Zmień słowo albo pisz dalej.";
/** The same, for the files of an `@`. */
export const NO_FILE_MATCH_MESSAGE = "Żaden plik nie pasuje. Zmień słowo albo pisz dalej.";
/** The built-in commands of the agents, the small list the design names. */
export const BUILTINS = {
"claude-code": [
{ key: "clear", desc: "Czyści historię rozmowy." },
{ key: "compact", desc: "Ścisza historię do podsumowania." },
{ key: "model", desc: "Wybiera model." },
{ key: "permissions", desc: "Ustawia uprawnienia narzędzi." },
{ key: "config", desc: "Otwiera ustawienia." },
{ key: "resume", desc: "Wznawia wcześniejszą sesję." },
],
codex: [
{ key: "model", desc: "Wybiera model." },
{ key: "approvals", desc: "Ustawia sposób zatwierdzania poleceń." },
{ key: "new", desc: "Zaczyna nową sesję." },
{ key: "resume", desc: "Wznawia wcześniejszą sesję." },
],
};
/** The same agent under the name the program's table gives it. */
const AGENT_ALIASES = { claude: "claude-code" };
/** How many files the `@` menu shows at most. */
const FILE_LIMIT = 20;
/** The project's command files, as a shell finds them. */
const LIST_SH =
'for f in .claude/commands/*.md .claude/skills/*/SKILL.md; do [ -f "$f" ] && printf \'%s\\n\' "$f"; done; exit 0';
/** The same in PowerShell, for a machine without a POSIX shell. */
const LIST_PS =
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); " +
"@(Get-ChildItem -Path '.claude/commands/*.md','.claude/skills/*/SKILL.md' -File -ErrorAction SilentlyContinue) " +
"| ForEach-Object { Resolve-Path -Relative -LiteralPath $_.FullName }";
/** Reading one file with a POSIX shell. */
const READ_SH = 'cat -- "$1"';
/**
* How long to wait before the next try after a read failed. The last wait
* repeats: the composer keeps trying every 30 s until the catalog is read.
*
* @param {number} attempt - 0 for the first wait
* @returns {number} milliseconds
*/
export function retryDelay(attempt) {
const index = Number.isFinite(attempt) ? Math.max(0, Math.floor(attempt)) : 0;
return RETRY_DELAYS[Math.min(index, RETRY_DELAYS.length - 1)];
}
/**
* The commands the `/` menu offers: the agent's built-ins, the project's own
* and the person's snippets.
*
* A source that cannot be read does not take the others with it: the menu
* shows what is known and the failure goes to `onReadError`, so the caller
* can tell a catalog it could not read from one with nothing to show.
* Without a handler the call rejects - the failure is never swallowed.
*
* @param {string} cwd - the folder of the pane
* @param {Exec} exec
* @param {{agent?:string, snippets?:object[], onReadError?:(error:Error) => void}} [options]
* @returns {Promise<Item[]>}
*/
export async function commands(cwd, exec, options = {}) {
const builtins = builtinItems(options.agent);
const snippets = snippetItems(options.snippets);
let project = [];
try {
project = await projectItems(cwd, exec);
} catch (err) {
// Nobody to tell: the caller gets the failure instead of a list that
// looks empty - an empty list would say "nothing fits" and the caller
// would never try again.
if (options.onReadError) options.onReadError(err);
else throw err;
}
return [...builtins, ...project, ...snippets];
}
/**
* The files the `@` menu offers: the ones git tracks in the pane's folder.
*
* The best matches come first and only then are they cut to twenty - a file
* that fits is never hidden behind twenty names that do not. Without a
* handler the call rejects when git fails.
*
* @param {string} cwd - the folder of the pane
* @param {Exec} exec
* @param {{needle?:string, limit?:number, onReadError?:(error:Error) => void}} [options]
* @returns {Promise<Item[]>}
*/
export async function files(cwd, exec, options = {}) {
const needle = String(options.needle ?? "").toLowerCase();
const limit = Number.isFinite(options.limit) ? options.limit : FILE_LIMIT;
let paths = [];
try {
paths = await gitFiles(cwd, exec);
} catch (err) {
// Nobody to tell: the caller gets the failure instead of an empty list
// that would say "nothing fits".
if (options.onReadError) options.onReadError(err);
else throw err;
}
const items = paths.map((path) => ({ key: path, desc: "", insert: `@${path} ` }));
return rank(items, needle, { atLineStart: true }).slice(0, limit);
}
/** The built-in commands of one agent - an agent we do not know has none. */
function builtinItems(agent) {
const name = String(agent ?? "");
const list = BUILTINS[name] ?? BUILTINS[AGENT_ALIASES[name]];
if (!list) return [];
return list.map((item) => ({
key: item.key,
desc: item.desc,
group: GROUP_BUILTIN,
insert: `/${item.key} `,
}));
}
/** The commands the project has: its command files and its skills. */
async function projectItems(cwd, exec) {
const { kind, paths } = await listProjectFiles(cwd, exec);
const items = [];
for (const path of paths) {
const name = commandName(path);
if (!name) continue;
const text = await readFile(cwd, exec, path, kind);
if (text === null) continue;
items.push({ key: name, desc: describe(text), group: GROUP_PROJECT, insert: `/${name} ` });
}
return items;
}
/** The person's own snippets, as the view read them from the storage. */
function snippetItems(snippets) {
if (!Array.isArray(snippets)) return [];
const items = [];
for (const snippet of snippets) {
const key = String(snippet?.key ?? snippet?.name ?? "").trim();
if (!key) continue;
const item = {
key,
desc: String(snippet?.desc ?? snippet?.description ?? ""),
group: GROUP_USER,
insert: `/${key} `,
};
if (Number.isFinite(snippet?.uses)) item.uses = snippet.uses;
items.push(item);
}
return items;
}
/**
* The project's command files. A POSIX shell is asked first - it is what a
* Linux or macOS machine has - and PowerShell after it, for a Windows machine
* without one. Neither is there: the catalog could not be read.
*/
async function listProjectFiles(cwd, exec) {
const viaShell = await tryList(exec, "sh", ["-c", LIST_SH, "catalog"], cwd, false);
if (viaShell) return { kind: "sh", paths: viaShell };
const viaPowerShell = await tryList(
exec,
"powershell",
["-NoProfile", "-Command", LIST_PS],
cwd,
true,
);
if (viaPowerShell) return { kind: "powershell", paths: viaPowerShell };
throw new Error("nie udało się wczytać katalogu projektu");
}
/** One listing, or `null` when the program is not there or it failed. */
async function tryList(exec, command, args, cwd, windowsPaths) {
let result;
try {
result = await exec(command, args, { cwd });
} catch {
return null;
}
if (!result || result.code !== 0) return null;
return String(result.stdout ?? "")
.split("\n")
.map((line) => {
const path = line.trim();
// PowerShell writes the separators of its own platform.
return windowsPaths ? path.replace(/\\/g, "/") : path;
})
.filter(Boolean);
}
/**
* One file of the project. The file may be gone between the listing and the
* read - then it is left out of the menu, not a reason to fail the catalog.
*/
async function readFile(cwd, exec, path, kind) {
const shells = kind === "sh" ? ["sh", "powershell"] : ["powershell", "sh"];
for (const shell of shells) {
const text = await tryRead(exec, shell, path, cwd);
if (text !== null) return text;
}
return null;
}
/** One read, or `null` when the file is not there or cannot be read. */
async function tryRead(exec, shell, path, cwd) {
const args =
shell === "sh"
? ["-c", READ_SH, "catalog", path]
: ["-NoProfile", "-Command", readScript(path)];
let result;
try {
result = await exec(shell, args, { cwd });
} catch {
return null;
}
if (!result || result.code !== 0) return null;
return String(result.stdout ?? "");
}
/** The PowerShell that reads one file; the path goes in as a literal. */
function readScript(path) {
const literal = path.replace(/'/g, "''");
return (
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); " +
// A file that is gone writes nothing and says nothing - the command
// would be a ghost. Without the encoding, Windows PowerShell reads a file
// without a BOM as the system's own code page, and the text comes out
// garbled.
`if (-not (Test-Path -LiteralPath '${literal}')) { exit 1 }; ` +
`Get-Content -Raw -Encoding utf8 -ErrorAction Stop -LiteralPath '${literal}'`
);
}
/** The name of the command a file holds: the file's name, or a skill's folder. */
function commandName(path) {
const parts = path.split("/");
const file = parts[parts.length - 1] ?? "";
if (file.toLowerCase() === "skill.md") return parts[parts.length - 2] ?? "";
return file.replace(/\.md$/i, "");
}
/**
* What the menu says about a command: the description of the front matter if
* there is one, else the first line that says something.
*/
function describe(markdown) {
const { fields, body } = frontmatter(String(markdown ?? ""));
if (fields.description) return clip(fields.description);
const line = body
.split("\n")
.map((part) => part.trim())
.find((part) => part !== "" && !part.startsWith("#"));
return clip(line ?? "");
}
/** The front matter of a markdown file, if it has one. */
function frontmatter(text) {
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
if (!match) return { fields: {}, body: text };
const fields = {};
for (const line of match[1].split(/\r?\n/)) {
const field = /^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/.exec(line);
if (!field) continue;
fields[field[1].toLowerCase()] = field[2].trim().replace(/^["']|["']$/g, "");
}
return { fields, body: text.slice(match[0].length) };
}
/** One line of text, no longer than the menu has room for. */
function clip(text) {
const flat = String(text).replace(/\s+/g, " ").trim();
if (flat.length <= 160) return flat;
return `${flat.slice(0, 160).replace(/\s\S*$/, "")}…`;
}
/**
* The files git tracks in the folder. `-z` keeps the names as they are - git
* would otherwise write a name with a non-ASCII character in it quoted and
* escaped.
*/
async function gitFiles(cwd, exec) {
let result;
try {
result = await exec("git", ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], {
cwd,
});
} catch (err) {
throw new Error(`nie udało się wczytać plików: ${err?.message ?? String(err)}`);
}
if (!result || result.code !== 0) {
const stderr = String(result?.stderr ?? "");
// A folder that is not a repository has no files to offer - that is an
// empty list, not a catalog that could not be read.
if (result?.code === 128 && /repo/i.test(stderr)) return [];
throw new Error(
`nie udało się wczytać plików: ${stderr.trim() || `git zakończone kodem ${result?.code}`}`,
);
}
return String(result.stdout ?? "")
.split("\0")
.map((path) => path.trim())
.filter(Boolean);
}
+268
View File
@@ -0,0 +1,268 @@
// delivery.js - sending, the queue and the turn gate.
//
// Plain ES module: no gpui-kit, no gpui-base, no herdr. The `hc` runner is
// injected (ctx.hc), so the whole delivery layer runs in plain Node
// (tests/delivery.test.mjs) without the app.
//
// The state model is the only writer: drain takes the state, moves the entry
// through `reduce` and hands a new state back. Nothing here changes a queue
// on its own.
//
// FACT (measured 2026-11-17 on herdr-core 0.1.16, `hc send --json`):
// `hc send` returns {"started":null,"status":null,"turn":0} and exits 0 - also
// for a plain shell with no agent, and also when it fails. Neither the exit
// code nor those fields say whether the agent got the message. Therefore:
// - ok:true means "the text was pasted and Enter pressed", NOT "the agent
// received it" - the UI says "Wysłano do terminala";
// - the only failure is a non-zero exit code (its stderr becomes the notice);
// - every `--json` call checks the payload for an "error" field, because `hc`
// exits 0 even on error (measured: `hc wait t3 --json` for a missing
// terminal -> {"error":{"kind":"not_found",...}}, exit 0);
// - a payload that is not JSON at all is an unknown result, not a success;
// - delivery confirmation comes from the agent's status (agents() /
// `hc get <t> --json`), never from the result of `hc send`;
// - exit codes are not mapped to meanings (9/11 - unproven, against the
// measurement);
// - the runner's `ok` flag carries no information the exit code does not
// already carry, so only the code and the payload are looked at.
import { reduce } from "./state.js";
/**
* @typedef {"idle"|"working"|"blocked"|"done"} Status
*
* @typedef {object} HcResult
* @property {boolean} [ok]
* @property {number} code
* @property {string} stdout
* @property {string} stderr
*
* @typedef {object} Ctx
* @property {string} terminal
* @property {(args:string[]) => Promise<HcResult>} hc
*
* @typedef {object} DrainCtx
* @property {string} agent - whose queue this is; the queue is `state.queue[agent]`
* @property {string} terminal
* @property {(args:string[]) => Promise<HcResult>} hc
* @property {() => Status} status
* @property {() => boolean} gate
* @property {(state:object) => void} [onState] - the caller persists the state
* here; it is called after every transition, the first time while the entry
* is on the wire (before the send runs), so a crash during the send leaves
* "sending" on disk and not "queued"
*
* @typedef {{ok:true} | {ok:false, code:number, message:string}} Result
* @typedef {{kind:"send"|"queue"|"hold"}} Decision
* @typedef {{state:object, sent:boolean, id?:string, reason?:string}} DrainResult
*
* @typedef {object} QueueItem
* @property {string} id
* @property {string} text
* @property {"queued"|"sending"|"held"|"uncertain"} state
* @property {number} createdAt
* @property {string} [reason]
*/
/**
* What to do with a message, given the agent's status.
*
* @param {Status|string} status
* @returns {Decision}
*/
export function decide(status) {
switch (status) {
case "idle":
case "done":
return { kind: "send" };
case "working":
return { kind: "queue" };
case "blocked":
return { kind: "hold" };
default:
// A status we do not know (the core also reports "error") - wait for a
// known one instead of pasting into an agent that may not be there.
return { kind: "queue" };
}
}
/**
* The turn gate: the next message goes out only after a whole turn was seen -
* the agent was working and then came back to idle/done. Without that
* transition a message could land in the middle of the agent's turn.
*
* @param {Status|string} status
* @param {boolean} seenWorking
* @returns {boolean}
*/
export function gateAfter(status, seenWorking) {
if (!seenWorking) return false;
return status === "idle" || status === "done";
}
/**
* Paste the text into the terminal and press Enter.
*
* `ok:true` means the text was pasted - not that the agent read it. The only
* failure is a non-zero exit code, an "error" in the `--json` payload, or a
* payload that is not JSON at all.
*
* @param {Ctx} ctx
* @param {string} text
* @returns {Promise<Result>}
*/
export async function sendNow(ctx, text) {
const res = await callHc(ctx, ["send", ctx.terminal, text, "--json"]);
if (res.failure) {
// The runner itself failed - there is no exit code to report.
return { ok: false, code: 0, message: res.failure };
}
if (res.code !== 0) {
return {
ok: false,
code: res.code,
message: res.stderr.trim() || `hc send zakończone kodem ${res.code}`,
};
}
const payload = parseJson(res.stdout);
if (!isPayload(payload)) {
// An unknown result is not a success: the text may or may not have gone
// out, so the caller must not treat this as delivered.
return { ok: false, code: res.code, message: "Nieznany wynik hc send" };
}
const failure = errorFrom(payload);
if (failure) return { ok: false, code: res.code, message: failure };
return { ok: true };
}
/**
* Send the first queued entry of the agent's queue, if the agent is ready and
* the gate is open. The queue is `state.queue[ctx.agent]` - the queues are per
* agent, and the status and the gate belong to that one agent.
*
* The state model is the only writer: the entry is claimed (`sending`) before
* we wait for `hc`, so it is on the wire while the send runs. On success the
* entry leaves the queue; on a failure it becomes `uncertain` - never
* `queued`, because `hc` exits 0 even on error and the text may have gone
* out. Nothing is repeated on its own.
*
* Every transition is handed to `ctx.onState` (the caller persists it) before
* the next step - the first time while the entry is on the wire, so a crash
* during the send leaves `sending` on disk and the restart turns it into
* `uncertain` instead of sending the message a second time.
*
* The gate is the caller's (ctx.gate()); the caller also resets it (sawWorking
* = false) after a successful send.
*
* @param {DrainCtx} ctx
* @param {object} state - the composer's state
* @returns {Promise<DrainResult>}
*/
export async function drain(ctx, state) {
const agent = ctx.agent;
const items = state.queue?.[agent] ?? [];
const item = items.find(sendable);
if (!item) return { state, sent: false };
if (!ready(ctx.status())) return { state, sent: false };
if (!ctx.gate()) return { state, sent: false };
// On the wire before we wait for `hc`: a restart in the middle must find the
// entry as `sending` and turn it into `uncertain`.
const claimed = reduce(state, { type: "claim", agent, id: item.id });
ctx.onState?.(claimed);
const result = await sendNow(ctx, item.text);
if (result.ok) {
const sent = reduce(claimed, { type: "settle", agent, id: item.id, outcome: "sent" });
ctx.onState?.(sent);
return { state: sent, sent: true, id: item.id };
}
const failed = reduce(claimed, {
type: "settle",
agent,
id: item.id,
outcome: "uncertain",
reason: result.message,
});
ctx.onState?.(failed);
return { state: failed, sent: false, reason: result.message };
}
/**
* After a restart an entry that was on the wire is `uncertain`: the message
* may or may not have reached the agent, so it is never sent again on its own.
*
* @param {QueueItem[]} queue
* @returns {QueueItem[]}
*/
export function onRestart(queue) {
if (!Array.isArray(queue)) return [];
return queue.map((item) => (item.state === "sending" ? { ...item, state: "uncertain" } : item));
}
/** The agent can take the next message when it is not working and not blocked. */
function ready(status) {
// "done" counts as ready: the core reports "done" for a turn that finished
// unseen, and it turns into "idle" only once somebody looks at it
// (herdr-app src/model.rs:596-604). A queue that waited for "idle" would
// never drain for an agent nobody watches.
return status === "idle" || status === "done";
}
/** Only an entry that waits in the queue may go out. */
function sendable(item) {
return item?.state === "queued";
}
/** Run `hc` and normalize what comes back. */
async function callHc(ctx, args) {
try {
const res = await ctx.hc(args);
return {
code: Number.isFinite(res?.code) ? res.code : 0,
stdout: typeof res?.stdout === "string" ? res.stdout : "",
stderr: typeof res?.stderr === "string" ? res.stderr : "",
failure: null,
};
} catch (err) {
return {
code: 0,
stdout: "",
stderr: "",
failure: err?.message ?? String(err),
};
}
}
/** The "error" of a `--json` payload, if it carries one. */
function errorFrom(payload) {
if (!payload.error) return null;
const err = payload.error;
if (typeof err === "string") return err;
if (typeof err.message === "string" && err.message) return err.message;
if (typeof err.kind === "string" && err.kind) return err.kind;
return JSON.stringify(err);
}
/** A `--json` payload is an object - anything else is an unknown result. */
function isPayload(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function parseJson(text) {
if (typeof text !== "string" || text.trim() === "") return null;
try {
return JSON.parse(text);
} catch {
return null;
}
}
+32
View File
@@ -0,0 +1,32 @@
{
"// why": [
"Written once by gpui-shell, then yours: an existing jsconfig.json or",
"tsconfig.json is never replaced, and this file is not rewritten.",
"",
"`moduleResolution` is how a bare specifier is answered. Left to be",
"inferred it can still land on the resolution that never looks in",
"node_modules, and a Git dependency the runtime resolves fine is",
"underlined as a module the editor cannot find.",
"",
"`lib` decides which globals exist. The default hands a script the",
"browser's — a `console`, a `localStorage`, a `Window` this runtime does",
"not have — and their declarations collide with the ones gpui-kit.d.ts makes,",
"so the file describing the API is itself reported as the error.",
"",
"`strictNullChecks` is off, and this one is the runtime's shape rather than",
"a preference. A view assigns its state in `init`, which TypeScript cannot",
"see as definite assignment the way it sees a constructor, so every field",
"would read as possibly-undefined and every use would want a `?.` that",
"means nothing at run time. Turning it on would buy noise, not safety."
],
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler",
"lib": ["ES2022"],
"checkJs": true,
"strict": true,
"strictNullChecks": false,
"noEmit": true
}
}
File diff suppressed because it is too large. Load diff
+4
View File
@@ -0,0 +1,4 @@
{
"place": "none",
"focusable": true
}
+312
View File
@@ -0,0 +1,312 @@
// state.js - the composer's state model.
//
// Pure: no GPUI, no herdr, no IO, no clock. `reduce` returns a new state and
// never mutates the one it was given, so the model can be tested in plain Node
// (tests/state.test.mjs) and reasoned about without a running app.
//
// Drafts, attachments and the queue are keyed by agent name ("claude-code",
// "codex"): each belongs to the agent it was written for, and switching agents
// must not lose any of them.
import { onRestart } from "./delivery.js";
/**
* @typedef {"image"|"file"} AttachmentKind
* @typedef {"ready"|"error"} AttachmentState
* @typedef {object} Attachment
* @property {string} id
* @property {string} name
* @property {string} path
* @property {number} bytes
* @property {AttachmentKind} kind
* @property {AttachmentState} state
* @property {string} [error]
*
* @typedef {"queued"|"sending"|"held"|"uncertain"} QueueItemState
* @typedef {object} QueueItem
* @property {string} id
* @property {string} text
* @property {QueueItemState} state
* @property {number} createdAt
* @property {string} [reason]
*
* @typedef {object} Notice
* @property {string} text
* @property {string} [level]
*
* @typedef {object} MenuState
* @property {boolean} open
* @property {string|null} trigger
* @property {object[]} items
* @property {number} index
*
* @typedef {object} State
* @property {Record<string,string>} drafts
* @property {Record<string,Attachment[]>} attachments
* @property {Record<string,QueueItem[]>} queue
* @property {Notice|null} notice
* @property {MenuState|null} menu
* @property {null} conflict
*/
/** @returns {State} */
export function createState() {
return {
drafts: {},
attachments: {},
queue: {},
notice: null,
menu: null,
conflict: null,
};
}
/**
* Is a message of this agent on the wire? The send state belongs to the agent,
* not to the composer: two agents may have one message each in flight, so a
* global flag would let one agent's settle clear the other's.
*
* @param {State} state
* @param {string} agent
* @returns {boolean}
*/
export function isSending(state, agent) {
return list(state.queue, agent).some((item) => item.state === "sending");
}
/**
* The one way the state changes. Never mutates `state`.
*
* @param {State} state
* @param {{type:string, agent?:string, id?:string, text?:string, file?:object, item?:object, items?:object[], notice?:object|null, outcome?:string, reason?:string}} action
* @returns {State}
*/
export function reduce(state, action) {
switch (action.type) {
case "draft":
return { ...state, drafts: { ...state.drafts, [action.agent]: action.text } };
case "send":
return { ...state, drafts: { ...state.drafts, [action.agent]: "" } };
case "attach":
return {
...state,
attachments: {
...state.attachments,
[action.agent]: [...list(state.attachments, action.agent), toAttachment(action.file)],
},
};
case "removeAttachment":
return {
...state,
attachments: {
...state.attachments,
[action.agent]: list(state.attachments, action.agent).filter((a) => a.id !== action.id),
},
};
case "queue":
return {
...state,
queue: {
...state.queue,
[action.agent]: [...list(state.queue, action.agent), toQueueItem(action.item)],
},
};
case "restore":
return restore(state, action);
case "discard":
return discard(state, action);
case "requeue":
return requeue(state, action);
case "claim":
return claim(state, action);
case "settle":
return settle(state, action);
case "restart":
return restart(state, action);
case "notice":
return { ...state, notice: action.notice ?? null };
default:
return state;
}
}
/**
* The queue of an agent comes back from the disk.
*
* The entries are put back as they were written - in the state they were in
* when the app went down. The `restart` action turns the ones that were on
* the wire into `uncertain`.
*/
function restore(state, action) {
const items = Array.isArray(action.items) ? action.items : [];
return {
...state,
queue: {
...state.queue,
[action.agent]: items.map((item) => ({ ...item })),
},
};
}
/**
* The entry is dropped: the person does not want it any more.
*
* Nothing is sent and nothing is written to the terminal - the entry only
* leaves the queue.
*/
function discard(state, action) {
const items = list(state.queue, action.agent);
if (!items.some((item) => item.id === action.id)) return state;
return {
...state,
queue: {
...state.queue,
[action.agent]: items.filter((item) => item.id !== action.id),
},
};
}
/**
* A held entry goes back to the queue.
*
* The hold said "the agent is waiting for you"; the person answered by asking
* for the message to go out anyway. The entry waits in the queue like any
* other and its reason goes with the hold. The turn gate of the agent is the
* view's business - it steps aside for a send outside a turn.
*/
function requeue(state, action) {
const items = list(state.queue, action.agent);
const item = items.find((entry) => entry.id === action.id);
if (!item || item.state !== "held") return state;
return {
...state,
queue: {
...state.queue,
[action.agent]: items.map((entry) =>
entry.id === action.id ? withoutReason({ ...entry, state: "queued" }) : entry,
),
},
};
}
/** The entry without its reason - the reason belonged to the hold. */
function withoutReason(item) {
const { reason, ...rest } = item;
return rest;
}
/**
* The entry goes on the wire: a `queued` entry becomes `sending`, and the
* composer shows it as in flight.
*
* Only `queued` entries are claimed. A `held` entry waits for the user and an
* `uncertain` one may already have reached the agent - claiming either of
* them would send the same message twice, so they stay as they are.
*/
function claim(state, action) {
const items = list(state.queue, action.agent);
const item = items.find((entry) => entry.id === action.id);
if (!item || item.state !== "queued") return state;
return {
...state,
queue: {
...state.queue,
[action.agent]: items.map((entry) =>
entry.id === action.id ? { ...entry, state: "sending" } : entry,
),
},
};
}
/**
* The entry's fate is known: `sent` drops it from the queue, `held` and
* `uncertain` keep it with a reason to show.
*/
function settle(state, action) {
const items = list(state.queue, action.agent);
if (!items.some((item) => item.id === action.id)) return state;
if (action.outcome === "sent") {
return {
...state,
queue: { ...state.queue, [action.agent]: items.filter((item) => item.id !== action.id) },
};
}
if (action.outcome !== "held" && action.outcome !== "uncertain") return state;
return {
...state,
queue: {
...state.queue,
[action.agent]: items.map((item) =>
item.id === action.id
? { ...item, state: action.outcome, ...(action.reason ? { reason: action.reason } : {}) }
: item,
),
},
};
}
/**
* The app restarted: an entry that was on the wire may or may not have reached
* the agent, so it becomes `uncertain` - it is never sent again on its own.
* Only the queue of that agent is touched.
*/
function restart(state, action) {
const items = list(state.queue, action.agent);
if (items.length === 0) return state;
return {
...state,
queue: {
...state.queue,
[action.agent]: onRestart(items),
},
};
}
/** The list of one agent - an agent without entries yet has an empty list. */
function list(map, agent) {
return map[agent] ?? [];
}
/** The caller names the file; the model only fills in the defaults. */
function toAttachment(file) {
return {
id: file.id,
name: file.name,
path: file.path,
bytes: file.bytes,
kind: file.kind ?? "file",
state: file.state ?? "ready",
...(file.error !== undefined ? { error: file.error } : {}),
};
}
/** The caller names the entry and stamps it; the model defaults the rest. */
function toQueueItem(item) {
if (!item || !Number.isFinite(item.createdAt)) {
// A missing timestamp would sort as epoch 0 and silently misorder the
// queue - the caller has to say when the entry was written.
throw new TypeError("queue entry needs a createdAt timestamp");
}
return {
id: item.id,
text: item.text,
state: item.state ?? "queued",
createdAt: item.createdAt,
...(item.reason !== undefined ? { reason: item.reason } : {}),
};
}
+359
View File
@@ -0,0 +1,359 @@
// storage.js - what the composer keeps between runs.
//
// The store is injected: `store = { get(key): unknown, set(key, value): void }`.
// The view (Task 8) hands it `{ get: shared, set: setShared }` from the
// `herdr` module. `shared()` is app-wide and persisted in
// ~/.config/herdr-app/shared.json, so the history is the same in every pane
// and outlives the app. `localStorage` would be per mod copy - per pane - and
// would not outlive a restart.
//
// The queue has to outlive a crash in the middle of a send: Task 5's `drain`
// marks the entry `sending` BEFORE the send goes on the wire and hands the
// state to the caller through `ctx.onState`, so the caller writes it down at
// once. After a restart the composer loads the queue and turns `sending` into
// `uncertain` (the `restart` action of state.js) - the message may have
// reached the agent, so it is never sent again on its own.
//
// Reading never throws: a key that was never written, a value that is not a
// list, a store that is not there - the composer always gets a list to show.
// Writing rubbish does not throw either, but it does not write: the stored
// list stays as it was, so a bug in the caller cannot wipe the history. A
// store that cannot be written to at all throws - the queue on disk is what
// keeps a crash from sending a message twice, so that must not pass quietly.
//
// What comes back is checked: an entry that lost a field on the way to the
// disk is dropped, not handed to the view. A queue entry without a moment
// (`createdAt`) would make state.js throw, and one with a state it does not
// know would wait for ever - and a cut entry that came back would be sent
// again.
/**
* @typedef {object} Store
* @property {(key:string) => unknown} get
* @property {(key:string, value:unknown) => unknown} set
*
* @typedef {object} HistoryEntry
* @property {string} id
* @property {string} text
* @property {number} at
* @property {string} agent
* @property {string} space
* @property {string} spaceName
* @property {string} tab
* @property {string} pane
* @property {string|null} machine
* @property {string[]} attachments
* @property {"sent"|"queued"|"failed"} outcome
*
* @typedef {object} FavoriteEntry
* @property {string} id
* @property {string} text
* @property {number} at
* @property {string} agent
* @property {"history"|"manual"} source
*
* @typedef {object} QueueEntry
* @property {string} id
* @property {string} text
* @property {"queued"|"sending"|"held"|"uncertain"} state
* @property {number} createdAt
* @property {string} [reason]
*/
/** The states a queue entry may be in (the ones state.js knows). */
const QUEUE_STATES = new Set(["queued", "sending", "held", "uncertain"]);
/** The keys the composer writes into the shared store. */
export const KEYS = {
history: "ovis-composer.history",
favorites: "ovis-composer.favorites",
usage: "ovis-composer.usage",
/** The queue is per agent: `ovis-composer.queue:<agent>`. */
queue: "ovis-composer.queue",
};
/** How many entries the history keeps. */
export const HISTORY_LIMIT = 500;
/** How many entries the favourites keep. */
export const FAVORITES_LIMIT = 100;
/**
* The key of one agent's queue.
*
* @param {string} agent
* @returns {string}
*/
export function queueKey(agent) {
return `${KEYS.queue}:${agent}`;
}
/**
* The history of the sent messages.
*
* The list is chronological - the oldest entry first, the newest last - and
* the oldest entries drop out when the list grows over the limit.
*
* @param {Store} store
* @returns {HistoryEntry[]}
*/
export function loadHistory(store) {
return readList(store, KEYS.history, HISTORY_LIMIT, isTextEntry);
}
/**
* @param {Store} store
* @param {HistoryEntry[]} items
* @returns {void}
*/
export function saveHistory(store, items) {
writeList(store, KEYS.history, items, HISTORY_LIMIT, isTextEntry);
}
/**
* The favourites - the texts the person marked, kept apart from the history
* so they outlive a cleared history.
*
* @param {Store} store
* @returns {FavoriteEntry[]}
*/
export function loadFavorites(store) {
return readList(store, KEYS.favorites, FAVORITES_LIMIT, isTextEntry);
}
/**
* @param {Store} store
* @param {FavoriteEntry[]} items
* @returns {void}
*/
export function saveFavorites(store, items) {
writeList(store, KEYS.favorites, items, FAVORITES_LIMIT, isTextEntry);
}
/**
* The queue of one agent - the messages that wait for their turn.
*
* The state is what it was when it was written: an entry that was on the wire
* (`sending`) is still `sending` here after a restart, and the composer
* turns it into `uncertain` (state.js, the `restart` action). The queue is
* never sent again on its own.
*
* @param {Store} store
* @param {string} agent
* @returns {QueueEntry[]}
*/
export function loadQueue(store, agent) {
return readList(store, queueKey(agent), 0, isQueueEntry);
}
/**
* @param {Store} store
* @param {string} agent
* @param {QueueEntry[]} items
* @returns {void}
*/
export function saveQueue(store, agent, items) {
if (typeof agent !== "string" || agent === "") return;
writeList(store, queueKey(agent), items, 0, isQueueEntry);
}
/**
* How often each command was used - the numbers the ranking of the
* suggestions breaks its ties with (`suggest.rank` reads `item.uses`).
*
* The key is the key of the catalog (`catalog.js`): the name of the command
* without the slash - "review", not "/review" - because that is the name
* `suggest.rank` compares.
*
* @param {Store} store
* @returns {Record<string, number>}
*/
export function loadUsage(store) {
const raw = read(store, KEYS.usage);
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
const counts = {};
for (const [key, value] of Object.entries(raw)) {
if (typeof value === "number" && Number.isFinite(value) && value >= 0) counts[key] = value;
}
return counts;
}
/**
* @param {Store} store
* @param {Record<string, number>} counts - the key of the catalog, without
* the slash: "review", not "/review"
* @returns {void}
*/
export function saveUsage(store, counts) {
if (!counts || typeof counts !== "object" || Array.isArray(counts)) return;
const clean = {};
for (const [key, value] of Object.entries(counts)) {
if (typeof value === "number" && Number.isFinite(value) && value >= 0) clean[key] = value;
}
// Counts that are not counts are rubbish - they do not wipe the counters
// that are there. An empty map on purpose still clears them.
if (Object.keys(counts).length > 0 && Object.keys(clean).length === 0) return;
write(store, KEYS.usage, clean);
}
/**
* Read a list, dropping what is not a list, what is not an entry and what the
* limit leaves out. The oldest entries drop out - the list is chronological.
*
* @param {Store} store
* @param {string} key
* @param {number} limit - 0 for a list without a limit
* @param {(entry:Record<string, unknown>) => boolean} isValid
* @returns {any[]}
*/
function readList(store, key, limit, isValid) {
const list = toList(read(store, key), isValid);
if (!list) return [];
return limit > 0 ? list.slice(-limit) : list;
}
/**
* Write a list, dropping what is not an entry and what the limit leaves out.
*
* @param {Store} store
* @param {string} key
* @param {unknown} items
* @param {number} limit - 0 for a list without a limit
* @param {(entry:Record<string, unknown>) => boolean} isValid
* @returns {void}
*/
function writeList(store, key, items, limit, isValid) {
const source = listSource(items);
// Rubbish in - nothing is written, so the stored list stays as it was.
if (!source) return;
const list = toList(source, isValid) ?? [];
// A list that lost every entry is rubbish, not an empty list - writing it
// would wipe what is there.
if (source.length > 0 && list.length === 0) return;
write(store, key, limit > 0 ? list.slice(-limit) : list);
}
/**
* The list in a value, or nothing when the value is not a list. The entries
* that are not entries of this kind are rubbish and go.
*
* The entries keep the shape the caller wrote - what a history entry and what
* a queue entry look like is the caller's business, not the store's.
*
* @param {unknown} value
* @param {(entry:Record<string, unknown>) => boolean} isValid
* @returns {any[]|null}
*/
function toList(value, isValid) {
const source = listSource(value);
if (!source) return null;
return source.filter((entry) => isEntry(entry, isValid));
}
/**
* Is this an entry of the kind the list holds? An entry that lost a field on
* the way to the disk does not come back - the view and the state model would
* have to guess what is missing.
*
* @param {unknown} entry
* @param {(entry:Record<string, unknown>) => boolean} isValid
* @returns {boolean}
*/
function isEntry(entry, isValid) {
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return false;
return isValid(/** @type {Record<string, unknown>} */ (entry));
}
/**
* An entry the view can show - a history entry and a favourite have the same
* shape: a text and a moment.
*
* @param {Record<string, unknown>} entry
* @returns {boolean}
*/
function isTextEntry(entry) {
return isText(entry.id) && isText(entry.text) && isTime(entry.at);
}
/**
* A queue entry the state model can take.
*
* `createdAt` is what state.js insists on - without it the model throws - and
* the state has to be one it knows: an entry with a state of its own would
* wait for ever, and one that lost its state could be sent a second time.
*
* @param {Record<string, unknown>} entry
* @returns {boolean}
*/
function isQueueEntry(entry) {
return (
isText(entry.id) &&
isText(entry.text) &&
isTime(entry.createdAt) &&
QUEUE_STATES.has(entry.state)
);
}
/** Is this a text? */
function isText(value) {
return typeof value === "string";
}
/** Is this a moment in time (epoch ms)? */
function isTime(value) {
return typeof value === "number" && Number.isFinite(value);
}
/**
* The list a value holds: the value itself, or the `items` of the envelope
* the design wrote down (`{ items: [ … ] }`).
*
* @param {unknown} value
* @returns {unknown[]|null}
*/
function listSource(value) {
if (Array.isArray(value)) return value;
if (!value || typeof value !== "object") return null;
const envelope = /** @type {{items?: unknown}} */ (value);
return Array.isArray(envelope.items) ? envelope.items : null;
}
/**
* Read a value from the store. A store that fails gives nothing.
*
* @param {Store} store
* @param {string} key
* @returns {unknown}
*/
function read(store, key) {
try {
if (!store || typeof store.get !== "function") return null;
const value = store.get(key);
return value ?? null;
} catch {
return null;
}
}
/**
* Write a value into the store. A store that cannot be written to throws -
* the queue on disk is what keeps a crash from sending a message twice.
*
* @param {Store} store
* @param {string} key
* @param {unknown} value
* @returns {void}
*/
function write(store, key, value) {
if (!store || typeof store.set !== "function") {
throw new TypeError(`brak magazynu dla klucza ${key}`);
}
store.set(key, value);
}
+189
View File
@@ -0,0 +1,189 @@
// suggest.js - when the composer offers suggestions and which ones.
//
// Pure: no GPUI, no herdr, no IO, no clock. The module answers three
// questions - is the caret inside a `/` or `@` token (detect), which items fit
// what was typed (rank), and how the items sit in groups when nothing was
// typed (merge) - so it runs in plain Node (tests/suggest.test.mjs).
//
// The rules are the design's (§5): four levels of matching, ties broken by how
// often the item was used and then by its name. A `/` opens the menu only at
// the start of a line or after a space, so a path like /tmp/x is left alone;
// an `@` opens the file menu anywhere.
/**
* @typedef {object} Item
* @property {string} key - the name the needle is matched against
* @property {string} desc - one line about the item
* @property {string} [group] - Wbudowane | Projekt | Użytkownik | Terminal
* @property {string} insert - the text put into the field ("/review ")
* @property {number} [uses] - how often the person picked the item
*/
/** The built-in commands of the agent. */
export const GROUP_BUILTIN = "Wbudowane";
/** The commands of the project the pane sits in. */
export const GROUP_PROJECT = "Projekt";
/** The person's own saved snippets. */
export const GROUP_USER = "Użytkownik";
/** The commands the terminal itself understands. */
export const GROUP_TERMINAL = "Terminal";
/** The groups, in the order the menu shows them. */
export const GROUPS = [GROUP_BUILTIN, GROUP_PROJECT, GROUP_USER, GROUP_TERMINAL];
/** A name may start a word after one of these. */
const BOUNDARY = new Set([":", "-", "_", ".", "/"]);
/** A command name holds no space and no path separator - "/tmp/x" is a path. */
const COMMAND_QUERY = /^[^\s/\\]*$/;
/** A file name holds no space and is not empty. */
const FILE_QUERY = /^\S+$/;
/**
* The token at the caret: `null` when the caret is not inside one.
*
* A `/` counts only at the start of a line or after a space, and only when
* what follows can be a command name - a slash in the middle of a word (the
* second slash of /tmp/x) is a path, not a command. An `@` counts anywhere,
* but it needs at least one character of a name to complete.
*
* @param {string} text
* @param {number} caret - where the cursor is, between characters
* @returns {{trigger:"/"|"@", needle:string, start:number}|null}
*/
export function detect(text, caret) {
if (typeof text !== "string") return null;
if (!Number.isInteger(caret) || caret < 0 || caret > text.length) return null;
const lineStart = text.lastIndexOf("\n", Math.max(0, caret - 1)) + 1;
const slash = text.lastIndexOf("/", Math.max(0, caret - 1));
if (slash >= lineStart && (slash === lineStart || /\s/.test(text[slash - 1] ?? ""))) {
const needle = text.slice(slash + 1, caret);
if (COMMAND_QUERY.test(needle)) return { trigger: "/", needle, start: slash };
}
const at = text.lastIndexOf("@", Math.max(0, caret - 1));
if (at >= lineStart) {
const needle = text.slice(at + 1, caret);
if (FILE_QUERY.test(needle)) return { trigger: "@", needle, start: at };
}
return null;
}
/**
* Does this token start a line? The fuzzy levels of the ranking are for the
* start of a line only - in the middle of one a name is matched by its
* beginning or by a word boundary, so the composer never rewrites a path.
*
* @param {string} text
* @param {number} index - where the trigger sits
* @returns {boolean}
*/
export function startsLine(text, index) {
if (typeof text !== "string") return true;
if (!Number.isInteger(index) || index <= 0) return true;
return text[index - 1] === "\n";
}
/**
* The items that fit the needle, best first.
*
* Four levels: the name begins with the needle (0), the needle sits at a
* word boundary of the name (1), the needle is somewhere in the name (2),
* the needle is in the description and is at least two characters long (3).
* Ties go to the item used more often, then to the name.
*
* The fuzzy levels (2 and 3) belong to a trigger at the start of a line -
* in the middle of one a name is matched by its beginning or by a word
* boundary, so the composer never rewrites a path. `atLineStart` says which
* of the two it is, and the caller has to say: without it the levels are off.
*
* @param {Item[]} items
* @param {string} needle
* @param {{atLineStart?:boolean}} [options] - `atLineStart: true` lets the
* fuzzy levels (2 and 3) in, for a trigger at the start of a line
* @returns {Item[]}
*/
export function rank(items, needle, options = {}) {
const atLineStart = options.atLineStart === true;
const query = typeof needle === "string" ? needle.toLowerCase() : "";
const list = Array.isArray(items) ? items : [];
const scored = [];
for (const item of list) {
if (!item) continue;
const level = levelOf(item, query);
if (level === null) continue;
if (!atLineStart && level > 1) continue;
scored.push({ item, level });
}
scored.sort((a, b) => {
if (a.level !== b.level) return a.level - b.level;
const used = (b.item.uses ?? 0) - (a.item.uses ?? 0);
if (used !== 0) return used;
return byName(a.item.key, b.item.key);
});
return scored.map((entry) => entry.item);
}
/**
* The items of every group in one list, the groups in the order the design
* names them. Used when nothing was typed - with a needle the list is flat.
*
* @param {Record<string, Item[]>} groups
* @returns {Item[]}
*/
export function merge(groups) {
const source = groups && typeof groups === "object" ? groups : {};
const names = [...GROUPS, ...Object.keys(source).filter((name) => !GROUPS.includes(name))];
const merged = [];
for (const name of names) {
const list = source[name];
if (!Array.isArray(list)) continue;
for (const item of list) {
if (!item) continue;
merged.push({ ...item, group: item.group ?? name });
}
}
return merged;
}
/**
* How well an item matches the needle; lower is better, `null` is no match.
*/
function levelOf(item, query) {
const name = String(item.key ?? "").toLowerCase();
const desc = String(item.desc ?? "").toLowerCase();
if (query === "") return 0;
if (name.startsWith(query)) return 0;
if (atBoundary(name, query)) return 1;
if (name.includes(query)) return 2;
if (query.length >= 2 && desc.includes(query)) return 3;
return null;
}
/** Does the needle sit after a word boundary anywhere in the name? */
function atBoundary(name, query) {
let at = name.indexOf(query);
while (at > 0) {
if (BOUNDARY.has(name[at - 1])) return true;
at = name.indexOf(query, at + 1);
}
return false;
}
/** Names in alphabetical order, the case not counting. */
function byName(a, b) {
const left = String(a ?? "").toLowerCase();
const right = String(b ?? "").toLowerCase();
if (left < right) return -1;
if (left > right) return 1;
return 0;
}
+464
View File
@@ -0,0 +1,464 @@
// view.js - the parts of the composer that need no GPUI and no app.
//
// Pure: no gpui-kit, no herdr, no IO, no clock. The view (main.js) asks its
// questions here, so that Node can check the answers (tests/main.test.mjs)
// without a running Herdr.
//
// The composer talks to one agent at a time - the focused one. Everything that
// belongs to an agent (the draft, the queue, the attachments) is keyed by the
// agent's address, so two Claude Code agents never share a draft.
import { drain, gateAfter } from "./delivery.js";
import { LIMITS } from "./attachments.js";
/**
* The agent the composer talks to.
*
* The focused terminal's agent first - that is the pane the person is
* looking at. An agent block that is shown (a layout that draws one agent)
* counts when no terminal has the focus. Without either there is nobody to
* write to, and the composer stays inactive.
*
* @param {object[]} agents - the live agents of the app
* @param {object|null} focused - the live focus of the window
* @returns {object|null} the agent, or null
*/
export function targetAgent(agents, focused) {
const list = Array.isArray(agents) ? agents : [];
if (!focused || typeof focused !== "object") return null;
const byTerminal = list.find((agent) => agent && agent.address === focused.terminal);
if (byTerminal) return byTerminal;
const byAgent = list.find((agent) => agent && agent.address === focused.agent);
return byAgent ?? null;
}
/**
* The key a draft, a queue and a set of attachments belong to.
*
* The address of the agent, not the name of its program: two Claude Code
* agents are two agents, and their drafts and queues must not mix.
*
* @param {object} agent
* @returns {string}
*/
export function agentKey(agent) {
if (!agent || typeof agent !== "object") return "";
const address = typeof agent.address === "string" ? agent.address.trim() : "";
if (address) return address;
return agentName(agent);
}
/**
* The name of the agent's program ("claude-code") - what the catalog of the
* built-in commands knows.
*
* @param {object} agent
* @returns {string}
*/
export function agentName(agent) {
if (!agent || typeof agent !== "object") return "default";
const app = typeof agent.app === "string" ? agent.app.trim() : "";
if (app) return app;
const key = typeof agent.program?.key === "string" ? agent.program.key.trim() : "";
return key || "default";
}
/**
* The status of an agent: "idle" when there is none to be had.
*
* @param {object} agent
* @returns {string}
*/
export function agentStatus(agent) {
const status = agent && typeof agent.status === "string" ? agent.status.trim() : "";
return status || "idle";
}
/**
* The turn gate of one agent.
*
* @returns {{sawWorking:boolean, open:boolean}}
*/
export function createGate() {
return { sawWorking: false, open: false };
}
/**
* May the next message go out?
*
* The gate opens after a whole turn was seen - the agent was working and came
* back to idle. A send outside a turn (the "Wyślij teraz" button) opens it
* outright, because it does not wait for a turn at all.
*
* @param {{sawWorking?:boolean, open?:boolean}} gate
* @param {string} status
* @returns {boolean}
*/
export function gatePasses(gate, status) {
if (!gate || typeof gate !== "object") return false;
if (gate.open === true) return true;
return gateAfter(status, gate.sawWorking === true);
}
/**
* The gate of an agent with the turn step aside.
*
* @param {{sawWorking?:boolean, open?:boolean}} gate
* @returns {{sawWorking:boolean, open:boolean}}
*/
export function openGate(gate) {
return { ...(gate ?? createGate()), open: true };
}
/**
* The gate closes again: the next message waits for the next turn.
*
* @param {{sawWorking?:boolean, open?:boolean}} gate
* @returns {{sawWorking:boolean, open:boolean}}
*/
export function closeGate(gate) {
return { ...(gate ?? createGate()), sawWorking: false, open: false };
}
/**
* Is this the Enter that sends the message?
*
* Shift+Enter is a new line. The secondary Enter - the one an IME sends when
* it confirms a composition - does not send either (Ovis: "IME Enter ignored").
*
* @param {{shift?:boolean, secondary?:boolean}} event
* @returns {boolean}
*/
export function isPlainEnter(event) {
if (!event) return false;
if (event.shift === true) return false;
if (event.secondary === true) return false;
return true;
}
/**
* The caret one line up or down.
*
* The field of this app version (gpui-base in herdr-app 0.1.16) does not move
* the cursor up and down by itself, so the composer does it: the caret goes to
* the same column of the line above (or below) and never leaves the text.
*
* @param {string} text
* @param {number} caret
* @param {number} step - negative for up, positive for down
* @returns {number} the new caret
*/
export function moveCaret(text, caret, step) {
const source = typeof text === "string" ? text : "";
const at = Number.isInteger(caret) ? caret : 0;
const here = Math.max(0, Math.min(at, source.length));
const lineStart = source.lastIndexOf("\n", here - 1) + 1;
const column = here - lineStart;
if (step < 0) {
if (lineStart === 0) return here; // there is no line above
const aboveEnd = lineStart - 1; // the newline of the line above
const aboveStart = source.lastIndexOf("\n", aboveEnd - 1) + 1;
return aboveStart + Math.min(column, aboveEnd - aboveStart);
}
const lineEnd = source.indexOf("\n", here);
if (lineEnd < 0) return here; // there is no line below
const belowStart = lineEnd + 1;
const nextBreak = source.indexOf("\n", belowStart);
const belowEnd = nextBreak < 0 ? source.length : nextBreak;
return belowStart + Math.min(column, belowEnd - belowStart);
}
/**
* What a key of the menu does.
*
* "none" — the composer does not touch the key: another field of the app has
* the keyboard, or there is no menu to move.
* "menu" — the arrows move the menu.
* "accept" — Tab takes the picked row.
*
* @param {boolean} hasKeyboard - does the composer's own field have the keyboard?
* @param {object|null} menu
* @param {string} key - "up", "down" or "tab"
* @returns {"none"|"menu"|"accept"}
*/
export function menuAction(hasKeyboard, menu, key) {
if (!hasKeyboard) return "none";
if (!menu || !(menu.items ?? []).length) return "none";
if (key === "up" || key === "down") return "menu";
if (key === "tab") return "accept";
return "none";
}
/**
* The JSON of a `--json` payload, or null when it is not JSON at all.
*
* @param {string} text
* @returns {object|null}
*/
export function parseJson(text) {
if (typeof text !== "string" || text.trim() === "") return null;
try {
const value = JSON.parse(text);
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
} catch {
return null;
}
}
/**
* May the composer count on this result of `hc`?
*
* `hc` exits 0 even when it fails, so the payload decides - and a payload
* that is not JSON at all is an unknown result, not a success (the same rule
* the delivery layer follows).
*
* @param {{code?:number, stdout?:string}|null} result
* @returns {boolean}
*/
export function hcOk(result) {
if (!result || result.code !== 0) return false;
const payload = parseJson(result.stdout);
return payload !== null && !payload.error;
}
/**
* What a send whose hook failed means.
*
* The hook of the delivery reports the states of the queue; a failure in it
* after the message went on the wire must not send the message again. The
* entry left the queue, so it is sent; an entry that is still there is
* uncertain.
*
* @param {object[]} queue - the queue of the agent
* @param {string} id
* @returns {"sent"|"uncertain"}
*/
export function failedHookOutcome(queue, id) {
const still = (Array.isArray(queue) ? queue : []).some((item) => item.id === id);
return still ? "uncertain" : "sent";
}
/**
* The queue goes out - one message after another, while the gate is open.
*
* `drain` sends one entry and leaves the gate as it was; the loop asks for the
* next one until the queue is empty or the gate closes. The caller keeps the
* "one drain in flight" flag for the whole loop: two drains on the same state
* would send the same message twice.
*
* @param {object} ctx - the ctx of `delivery.drain`
* @param {object} state
* @returns {Promise<{state:object, sent:number}>}
*/
export async function drainAll(ctx, state) {
let current = state;
let sent = 0;
for (;;) {
const result = await drain(ctx, current);
current = result.state;
if (!result.sent) break;
sent += 1;
}
return { state: current, sent };
}
/**
* What the composer says about an agent's status.
*
* @param {string} status
* @returns {string}
*/
export function statusText(status) {
switch (status) {
case "working":
return "pracuje";
case "blocked":
return "czeka na Ciebie";
case "done":
return "skończył";
default:
return "gotowy";
}
}
/**
* The label of a queue row.
*
* @param {{state?:string}} item
* @returns {string}
*/
export function queueLabel(item) {
switch (item?.state) {
case "queued":
return "Następna tura";
case "held":
return "Do wysłania teraz";
case "sending":
return "Wysyłanie…";
case "uncertain":
return "Niepotwierdzone";
default:
return "";
}
}
/**
* The text and the caret after a suggestion is accepted.
*
* The token at the caret is replaced by what the item inserts; the caret lands
* behind it, so the next word continues where the person was typing.
*
* @param {string} text
* @param {number} caret
* @param {{start?:number}} token - the trigger of the suggestion
* @param {string} insert
* @returns {{value:string, caret:number}}
*/
export function applySuggestion(text, caret, token, insert) {
const source = typeof text === "string" ? text : "";
const at = Number.isInteger(caret) ? caret : 0;
const start = Number.isInteger(token?.start) ? token.start : at;
const value = source.slice(0, start) + String(insert ?? "") + source.slice(at);
return { value, caret: start + String(insert ?? "").length };
}
/**
* The newline that Enter put into the field.
*
* The composer sends on Enter, and the field puts a newline in before the
* submit arrives. The message is the text as it was before that newline - and
* the caret is where the newline went in.
*
* @param {string} previous - the text before the change
* @param {string} next - the text after the change
* @returns {{index:number}|null} where the newline went in, or null
*/
export function insertedNewline(previous, next) {
if (typeof previous !== "string" || typeof next !== "string") return null;
if (next.length !== previous.length + 1) return null;
for (let index = 0; index < next.length; index += 1) {
if (next[index] !== "\n") continue;
if (next.slice(0, index) + next.slice(index + 1) === previous) return { index };
}
return null;
}
/**
* The mentions of the files, at the start of the message.
*
* A leading command keeps the first place - the mentions follow it.
*
* @param {string} text
* @param {string[]} tokens - the mentions ("@src/a.rs")
* @returns {{value:string, caret:number}}
*/
export function insertMentions(text, tokens) {
const source = typeof text === "string" ? text : "";
const list = (Array.isArray(tokens) ? tokens : []).filter(Boolean);
if (list.length === 0) return { value: source, caret: source.length };
const command = /^\/[^\s]*\s*/.exec(source);
const at = command ? command[0].length : 0;
const mentions = list.map((token) => `${token} `).join("");
return {
value: source.slice(0, at) + mentions + source.slice(at),
caret: at + mentions.length,
};
}
/**
* The items of the catalog, grouped by their group.
*
* @param {object[]} items
* @returns {Record<string, object[]>}
*/
export function groupItems(items) {
const groups = {};
for (const item of Array.isArray(items) ? items : []) {
if (!item) continue;
const name = typeof item.group === "string" && item.group !== "" ? item.group : "";
if (!groups[name]) groups[name] = [];
groups[name].push(item);
}
return groups;
}
/**
* The folder and the branch of the pane the composer talks to.
*
* @param {object[]} panes
* @param {string} terminal
* @returns {{cwd:string|null, branch:string|null}}
*/
export function paneContext(panes, terminal) {
const list = Array.isArray(panes) ? panes : [];
const pane = list.find((entry) => entry && entry.terminal === terminal);
return { cwd: pane?.cwd ?? null, branch: pane?.branch ?? null };
}
/**
* The last parts of a path - the folder the person knows by heart.
*
* @param {string} path
* @returns {string}
*/
export function shortPath(path) {
const parts = String(path ?? "")
.split(/[\\/]/)
.filter(Boolean);
if (parts.length <= 2) return parts.join("/");
return parts.slice(-2).join("/");
}
/**
* A store that never writes back a list it failed to read.
*
* The reader of storage.js swallows a failing read and answers with an empty
* list - writing that list back would wipe what is really there. The store
* remembers which keys failed and refuses to write them.
*
* @param {{get:(key:string)=>unknown, set:(key:string, value:unknown)=>unknown}} raw
* @returns {{get:(key:string)=>unknown, set:(key:string, value:unknown)=>void, failed:(key:string)=>boolean}}
*/
export function guardedStore(raw) {
const failed = new Set();
return {
get(key) {
try {
const value = raw.get(key);
return value ?? null;
} catch {
failed.add(key);
return null;
}
},
set(key, value) {
if (failed.has(key)) return;
raw.set(key, value);
},
failed(key) {
return failed.has(key);
},
};
}
/**
* How many characters the text has over the limit (0 when it fits).
*
* @param {string} text
* @returns {number}
*/
export function overLimit(text) {
const length = typeof text === "string" ? text.length : 0;
return Math.max(0, length - LIMITS.messageChars);
}