Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: quieter self-check notes and safer notes guard

ogsamrat73c024542099
diff --git a/apps/server/src/agent-assist-config.test.ts b/apps/server/src/agent-assist-config.test.ts
index 8ab58532..df00358d 100644
--- a/apps/server/src/agent-assist-config.test.ts
+++ b/apps/server/src/agent-assist-config.test.ts
@@ -17,6 +17,7 @@ import {
agentAssistFlags,
agentAssistForced,
agentAssistLspConfig,
+ lspHeapMb,
normalizeAgentAssistSetting,
writeAgentAssistFile,
} from "./agent-assist-config.js";
@@ -49,6 +50,10 @@ describe("agent assist", () => {
}
const config = { configPath: "/data/server.json" } as unknown as ServerConfig;
const env = agentAssistEngineEnv(config, { NODE_OPTIONS: "--trace-warnings" });
+ expect(lspHeapMb(4 * 1024 ** 3)).toBe(shared.lspHeapMb(4 * 1024 ** 3));
+ expect(lspHeapMb(64 * 1024 ** 3)).toBe(shared.lspHeapMb(64 * 1024 ** 3));
+ // Diagnostics off at the start: no heap cap in the engine's env.
+ expect(agentAssistEngineEnv(config, { NODE_OPTIONS: "--x" }, { diagnostics: false }).NODE_OPTIONS).toBeUndefined();
const expected: Record<string, string> = shared.lspEngineEnv({ NODE_OPTIONS: "--trace-warnings" });
expect({ NODE_OPTIONS: env.NODE_OPTIONS, OMNIRUSH_USER_NODE_OPTIONS: env.OMNIRUSH_USER_NODE_OPTIONS, OMNIRUSH_LSP_HEAP: env.OMNIRUSH_LSP_HEAP } as Record<string, string | undefined>).toEqual(expected);
});
diff --git a/apps/server/src/agent-assist-config.ts b/apps/server/src/agent-assist-config.ts
index 64c68ade..2149f050 100644
--- a/apps/server/src/agent-assist-config.ts
+++ b/apps/server/src/agent-assist-config.ts
@@ -20,6 +20,7 @@
* of the server's build output); agent-assist-config.test.ts keeps them equal.
*/
import { mkdir, readFile } from "node:fs/promises";
+import { totalmem } from "node:os";
import { join } from "node:path";
import { writeFileAtomic } from "./atomic-write.js";
@@ -48,6 +49,13 @@ export const LSP_BUILTIN_IDS = [
];
export const LSP_ENABLED_IDS = ["typescript", "deno", "pyright", "gopls", "rust"];
export const LSP_HEAP_MB = 3072;
+const LSP_HEAP_MIN_MB = 768;
+
+/** The servers' heap cap: LSP_HEAP_MB, at most a quarter of this machine's memory. */
+export function lspHeapMb(totalBytes = totalmem()): number {
+ const quarter = Math.floor(totalBytes / 4 / 1024 / 1024);
+ return Math.max(LSP_HEAP_MIN_MB, Math.min(LSP_HEAP_MB, quarter || LSP_HEAP_MB));
+}
function switchValue(value: string | undefined): boolean | null {
const text = String(value ?? "").trim().toLowerCase();
@@ -89,19 +97,21 @@ export function agentAssistFilePath(config: ServerConfig): string {
/**
* The engine's env: where the plugin reads its switches and keeps its notes,
- * and the language servers' heap cap (NODE_OPTIONS; the plugin puts the
- * person's own NODE_OPTIONS back for every shell call and terminal).
+ * and, while code diagnostics are on when the engine starts, the language
+ * servers' heap cap (NODE_OPTIONS; the plugin puts the person's own
+ * NODE_OPTIONS back for every shell call and terminal). Diagnostics turned on
+ * later run without the cap until the next start.
*/
-export function agentAssistEngineEnv(config: ServerConfig, env: NodeJS.ProcessEnv = process.env): Record<string, string> {
- const own = typeof env.NODE_OPTIONS === "string" ? env.NODE_OPTIONS : "";
- const capped = /--max-old-space-size[= ]/.test(own) ? own : `${own} --max-old-space-size=${LSP_HEAP_MB}`.trim();
- return {
+export function agentAssistEngineEnv(config: ServerConfig, env: NodeJS.ProcessEnv = process.env, { diagnostics = true, totalBytes }: { diagnostics?: boolean; totalBytes?: number } = {}): Record<string, string> {
+ const base = {
OMNIRUSH_AGENT_ASSIST_FILE: agentAssistFilePath(config),
OMNIRUSH_AGENT_ASSIST_DIR: join(runtimeStorageDir(config), "agent-assist"),
- NODE_OPTIONS: capped,
- OMNIRUSH_USER_NODE_OPTIONS: own,
- OMNIRUSH_LSP_HEAP: String(LSP_HEAP_MB),
};
+ if (!diagnostics) return base;
+ const heap = lspHeapMb(totalBytes);
+ const own = typeof env.NODE_OPTIONS === "string" ? env.NODE_OPTIONS : "";
+ const capped = /--max-old-space-size[= ]/.test(own) ? own : `${own} --max-old-space-size=${heap}`.trim();
+ return { ...base, NODE_OPTIONS: capped, OMNIRUSH_USER_NODE_OPTIONS: own, OMNIRUSH_LSP_HEAP: String(heap) };
}
/** Rewrites the plugin's switch file when the features changed. */
diff --git a/apps/server/src/agent-assist/PARITY.sha256 b/apps/server/src/agent-assist/PARITY.sha256
index b418ebe8..3940ab9d 100644
--- a/apps/server/src/agent-assist/PARITY.sha256
+++ b/apps/server/src/agent-assist/PARITY.sha256
@@ -1,4 +1,4 @@
# Agent assist modules that are the same files in omnirush-cli (assets/extensions/omnirush/agent-assist/)
# and omnirush-gui (apps/server/src/opencode-plugins/agent-assist/). A change to one must be ported to the other and this list updated in both.
-16e15511a9e87f8f1229594e5091f698e3949b2cb87d075d90f5764a74963c94 agent-assist.js
-80d3836aad7593354529e13dc7eb81a85604a81d5cb2dc8ce638d89e54d61d3e agent-assist-hooks.js
+a247f54af7fb805067ab23caa9d2cf029f2b149d8ff8ea237e069e3b5f3ec8d0 agent-assist.js
+af984a19b9b854f433267bb84b8a8956e9ee9a026d35ed05e3aac73cdf46bc7a agent-assist-hooks.js
diff --git a/apps/server/src/agent-assist/agent-assist-hooks.js b/apps/server/src/agent-assist/agent-assist-hooks.js
index b13dab43..a828ce35 100644
--- a/apps/server/src/agent-assist/agent-assist-hooks.js
+++ b/apps/server/src/agent-assist/agent-assist-hooks.js
@@ -2,36 +2,42 @@
// in omnirush-cli and omnirush-gui (see PARITY.sha256). Each app's plugin file
// only calls agentAssistHooks().
//
-// - Self-check: after a code edit, every model call of the turn gets a system
-// note to run the project's checks and fix what fails; a check's result is
-// read from the shell call (no extra tool), at most 3 failed rounds per turn,
-// "skip the tests" in the prompt turns it off for the turn. A toast shows
-// "Checked: 42 tests passed" / "Check failed: ..." / "Not checked".
+// - Self-check: after a code edit, the turn's model calls carry a note (an
+// in-memory part of the newest prompt, never stored, after the cached
+// history) to run the project's checks and fix what fails; a check's result
+// is read from the shell call (no extra tool), at most 3 failed rounds per
+// turn, "skip the tests" in the prompt turns it off for the turn. A toast
+// shows "Checked: 42 tests passed" / "Check failed: ..." / "Not checked".
// - Project notes: /init gets the repository facts read here; a change that
// would drop existing lines of AGENTS.md is refused once with the diff, so
-// the agent asks first; at a turn's end a toast offers /init when the
-// session found commands AGENTS.md lacks.
+// the agent asks first, and goes through only after a reply that is not a
+// refusal; at a turn's end a toast offers /init when the session found
+// commands AGENTS.md lacks.
// - Diagnostics: the language servers' "package not installed here" errors
// are left out of file tool results; their metadata is capped.
// - Compaction: the summary prompt gets more sections and the facts of the
// whole session; facts a summary leaves out stay beside it in the model's
// context (never stored in the chat).
+//
+// Its notes (compaction ledgers, a pending AGENTS.md question) live in
+// OMNIRUSH_AGENT_ASSIST_DIR (0700, files 0600, pruned after 30 days); without
+// that folder they are kept in memory only.
import fs from "node:fs";
-import os from "node:os";
import path from "node:path";
import {
FEATURES_FILE_ENV,
+ admitNote,
+ capDiagnosticsMetadata,
compactionContext,
+ declinesChange,
detectChecks,
devCommand,
featuresFromEnv,
filterDiagnosticsOutput,
- capDiagnosticsMetadata,
isCheckCommand,
isCodeEdit,
- admitNote,
latestSummary,
learnedCommands,
missingFactsNote,
@@ -53,17 +59,30 @@ const CHECKS_TTL_MS = 15_000;
const FLAGS_TTL_MS = 5_000;
const COMPACTING_MAX_MS = 10 * 60_000;
const LEDGER_MAX_AGE_MS = 15 * 60_000;
+const STATE_MAX_AGE_MS = 30 * 24 * 60 * 60_000;
function promptText(parts) {
if (!Array.isArray(parts)) return "";
return parts.filter((part) => part && part.type === "text" && !part.synthetic && typeof part.text === "string").map((part) => part.text).join("\n");
}
-function ledgerDir(env) {
- const dir = typeof env.OMNIRUSH_AGENT_ASSIST_DIR === "string" && env.OMNIRUSH_AGENT_ASSIST_DIR.trim()
- ? env.OMNIRUSH_AGENT_ASSIST_DIR.trim()
- : path.join(os.tmpdir(), `omnirush-agent-assist-${typeof process.getuid === "function" ? process.getuid() : "user"}`);
- return dir;
+function stateDir(env) {
+ const dir = typeof env.OMNIRUSH_AGENT_ASSIST_DIR === "string" ? env.OMNIRUSH_AGENT_ASSIST_DIR.trim() : "";
+ return dir || null;
+}
+
+/** Removes the folder's notes older than 30 days (sessions long gone). */
+function pruneState(dir, now) {
+ if (!dir) return;
+ let names = [];
+ try { names = fs.readdirSync(dir); } catch { return; }
+ for (const name of names) {
+ if (!/^(?:ledger-.*\.json|notes-pending-.*)$/.test(name)) continue;
+ try {
+ const file = path.join(dir, name);
+ if (now - fs.statSync(file).mtimeMs > STATE_MAX_AGE_MS) fs.rmSync(file, { force: true });
+ } catch { /* gone */ }
+ }
}
export function agentAssistHooks(input = {}, { env = process.env, now = () => Date.now(), log = () => undefined } = {}) {
@@ -75,13 +94,15 @@ export function agentAssistHooks(input = {}, { env = process.env, now = () => Da
return flagsCache.value;
};
const live = typeof env[FEATURES_FILE_ENV] === "string" && env[FEATURES_FILE_ENV].trim() !== "";
- const heap = typeof env.OMNIRUSH_LSP_HEAP === "string";
- if (!live && !heap && !Object.values(flags()).some(Boolean)) return {};
+ if (!live && typeof env.OMNIRUSH_LSP_HEAP !== "string" && !Object.values(flags()).some(Boolean)) return {};
const root = path.resolve(input.directory || input.worktree || process.cwd());
const client = input.client;
+ const dir = stateDir(env);
const sessions = new Map();
const ledgers = new Map();
+ const pendingInMemory = new Set();
let checksCache = { at: -Infinity, list: [] };
+ pruneState(dir, now());
const checks = () => {
if (now() - checksCache.at > CHECKS_TTL_MS) checksCache = { at: now(), list: detectChecks(root) };
@@ -98,35 +119,42 @@ export function agentAssistHooks(input = {}, { env = process.env, now = () => Da
const compacting = (st) => st.compactingSince > 0 && now() - st.compactingSince < COMPACTING_MAX_MS;
const toast = (title, message, variant = "info") => {
try {
- const sent = client?.tui?.showToast?.({ body: { title, message, variant, duration: 8000 } });
+ // The project's own engine instance: one engine serves several projects in the desktop app.
+ const sent = client?.tui?.showToast?.({ body: { title, message, variant, duration: 8000 }, query: { directory: root } });
if (sent && typeof sent.catch === "function") sent.catch(() => undefined);
} catch { /* the app shows no toast */ }
};
- const ledgerFile = (id) => path.join(ledgerDir(env), `ledger-${String(id).replace(/[^\w-]/g, "_")}.json`);
- // A refused AGENTS.md change waits for the person's answer, also across engine runs (headless -p turns).
- const pendingFile = (id) => path.join(ledgerDir(env), `notes-pending-${String(id).replace(/[^\w-]/g, "_")}`);
- const markPending = (id, on) => {
+ const safe = (id) => String(id).replace(/[^\w-]/g, "_");
+ const writeState = (name, content) => {
+ if (!dir) return;
try {
- if (on) {
- fs.mkdirSync(ledgerDir(env), { recursive: true, mode: 0o700 });
- fs.writeFileSync(pendingFile(id), "", { mode: 0o600 });
- } else fs.rmSync(pendingFile(id), { force: true });
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
+ fs.writeFileSync(path.join(dir, name), content, { mode: 0o600 });
} catch { /* memory only */ }
};
+ // A refused AGENTS.md change waits for the person's answer, also across engine runs (headless -p turns).
+ const markPending = (id, on) => {
+ if (on) pendingInMemory.add(id);
+ else pendingInMemory.delete(id);
+ if (on) writeState(`notes-pending-${safe(id)}`, "");
+ else if (dir) {
+ try { fs.rmSync(path.join(dir, `notes-pending-${safe(id)}`), { force: true }); } catch { /* gone */ }
+ }
+ };
const pending = (id) => {
- try { return fs.existsSync(pendingFile(id)); } catch { return false; }
+ if (pendingInMemory.has(id)) return true;
+ if (!dir) return false;
+ try { return fs.existsSync(path.join(dir, `notes-pending-${safe(id)}`)); } catch { return false; }
};
const saveLedger = (id, entry) => {
ledgers.set(id, entry);
- try {
- fs.mkdirSync(ledgerDir(env), { recursive: true, mode: 0o700 });
- fs.writeFileSync(ledgerFile(id), JSON.stringify(entry), { mode: 0o600 });
- } catch { /* memory only */ }
+ writeState(`ledger-${safe(id)}.json`, JSON.stringify(entry));
};
const loadLedger = (id) => {
if (ledgers.has(id)) return ledgers.get(id);
+ if (!dir) return null;
try {
- const entry = JSON.parse(fs.readFileSync(ledgerFile(id), "utf8"));
+ const entry = JSON.parse(fs.readFileSync(path.join(dir, `ledger-${safe(id)}.json`), "utf8"));
ledgers.set(id, entry);
return entry;
} catch {
@@ -142,6 +170,11 @@ export function agentAssistHooks(input = {}, { env = process.env, now = () => Da
return [];
}
};
+ /** A copy of `message` with one more in-memory text part (the stored chat is never changed). */
+ const withPart = (message, id, text) => {
+ const template = message.parts.find((part) => part?.type === "text") ?? { sessionID: message.info?.sessionID, messageID: message.info?.id };
+ return { ...message, parts: [...message.parts, { ...template, id: `${template.id ?? `prt_${message.info?.id ?? "x"}`}_${id}`, type: "text", text, synthetic: true }] };
+ };
const hooks = {};
@@ -151,39 +184,29 @@ export function agentAssistHooks(input = {}, { env = process.env, now = () => Da
if (!text) return; // the engine's own follow-ups (a synthetic "continue")
const st = session(info.sessionID);
noteUserPrompt(st.check, text);
- // The person answered after a refused AGENTS.md change: this turn may apply it.
- st.notesAllowed = st.notesBlocked || pending(info.sessionID);
- if (st.notesAllowed) markPending(info.sessionID, false);
+ // The person answered after a refused AGENTS.md change: this turn may apply it, unless the answer declines.
+ const asked = st.notesBlocked || pending(info.sessionID);
+ st.notesAllowed = asked && !declinesChange(text);
+ if (asked) markPending(info.sessionID, false);
st.notesBlocked = false;
};
- {
- hooks["experimental.chat.system.transform"] = async (info, output) => {
- if (!flags().selfCheck || !info?.sessionID || !Array.isArray(output?.system)) return;
- const st = sessions.get(info.sessionID);
- if (!st || compacting(st)) return;
- const note = admitNote(st.check, selfCheckNote(st.check, checks()));
- if (note) output.system.push(note);
- };
- }
+ hooks["tool.execute.before"] = async (info, output) => {
+ if (!flags().projectNotes || !FILE_TOOLS.has(String(info?.tool || "").toLowerCase())) return;
+ const drops = notesLinesDropped(info.tool, output?.args, root);
+ if (!drops.length) return;
+ const st = session(info.sessionID);
+ if (st.notesAllowed) return;
+ st.notesBlocked = true;
+ markPending(info.sessionID, true);
+ throw new Error(notesGuardMessage(drops));
+ };
- {
- hooks["tool.execute.before"] = async (info, output) => {
- if (!flags().projectNotes || !FILE_TOOLS.has(String(info?.tool || "").toLowerCase())) return;
- const drops = notesLinesDropped(info.tool, output?.args, root);
- if (!drops.length) return;
- const st = session(info.sessionID);
- if (st.notesAllowed) return;
- st.notesBlocked = true;
- markPending(info.sessionID, true);
- throw new Error(notesGuardMessage(drops));
- };
- hooks["command.execute.before"] = async (info, output) => {
- if (!flags().projectNotes || info?.command !== "init" || !Array.isArray(output?.parts)) return;
- const st = session(info.sessionID);
- output.parts.push({ type: "text", text: projectScan(root, { learned: learnedCommands(st.worked, root) }), synthetic: true });
- };
- }
+ hooks["command.execute.before"] = async (info, output) => {
+ if (!flags().projectNotes || info?.command !== "init" || !Array.isArray(output?.parts)) return;
+ const st = session(info.sessionID);
+ output.parts.push({ type: "text", text: projectScan(root, { learned: learnedCommands(st.worked, root) }), synthetic: true });
+ };
hooks["tool.execute.after"] = async (info, output) => {
if (!info?.sessionID || !output) return;
@@ -219,44 +242,54 @@ export function agentAssistHooks(input = {}, { env = process.env, now = () => Da
}
};
- {
- hooks["experimental.session.compacting"] = async (info, output) => {
- if (!flags().compaction || !info?.sessionID || !output) return;
- const st = session(info.sessionID);
- st.compactingSince = now();
- const ledger = sessionLedger(await sessionMessages(info.sessionID));
- saveLedger(info.sessionID, { at: now(), ledger });
- if (Array.isArray(output.context)) output.context.push(compactionContext(ledger));
- };
- hooks["experimental.chat.messages.transform"] = async (_info, output) => {
- const messages = output?.messages;
- if (!flags().compaction || !Array.isArray(messages) || messages.length === 0) return;
- const id = messages[0]?.info?.sessionID;
- if (!id) return;
- const st = sessions.get(id);
- const summary = latestSummary(messages);
- if (st && compacting(st)) {
- // The compaction's own request (no new summary yet), or the first one after it.
- if (!summary || summary.created < st.compactingSince) return;
- st.compactingSince = 0;
- }
- if (!summary) return;
+ hooks["experimental.session.compacting"] = async (info, output) => {
+ if (!info?.sessionID || !output) return;
+ const st = session(info.sessionID);
+ // Also with the summaries' extras off: no self-check note in the compaction request.
+ st.compactingSince = now();
+ if (!flags().compaction) return;
+ const ledger = sessionLedger(await sessionMessages(info.sessionID));
+ saveLedger(info.sessionID, { at: now(), ledger });
+ if (Array.isArray(output.context)) output.context.push(compactionContext(ledger));
+ };
+
+ // Every model call's messages (an in-memory copy; the stored chat is never changed).
+ hooks["experimental.chat.messages.transform"] = async (_info, output) => {
+ const messages = output?.messages;
+ if (!Array.isArray(messages) || messages.length === 0) return;
+ const id = messages[0]?.info?.sessionID;
+ if (!id) return;
+ const on = flags();
+ const st = sessions.get(id);
+ const summary = latestSummary(messages);
+ if (st && compacting(st)) {
+ // The compaction's own request (no new summary yet), or the first one after it.
+ if (!summary || summary.created < st.compactingSince) return;
+ st.compactingSince = 0;
+ }
+ if (on.compaction && summary) {
const entry = loadLedger(id);
- if (!entry || entry.at > summary.created + 60_000 || summary.created - entry.at > LEDGER_MAX_AGE_MS) return;
- const note = missingFactsNote(entry.ledger, summary.text);
- if (!note) return;
- const message = messages[summary.index];
- const template = message.parts.find((part) => part?.type === "text") ?? {};
- // A new object: the stored chat is never changed.
- messages[summary.index] = {
- ...message,
- parts: [...message.parts, { ...template, id: `${template.id ?? "prt"}_facts`, type: "text", text: note, synthetic: true }],
- };
- };
- }
+ if (entry && entry.at <= summary.created + 60_000 && summary.created - entry.at <= LEDGER_MAX_AGE_MS) {
+ const note = missingFactsNote(entry.ledger, summary.text);
+ if (note) messages[summary.index] = withPart(messages[summary.index], "facts", note);
+ }
+ }
+ if (on.selfCheck && st) {
+ // On the newest prompt: after the history the provider caches, so a note that comes and goes never re-sends it.
+ const note = admitNote(st.check, selfCheckNote(st.check, checks()));
+ if (note) {
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
+ if (messages[i]?.info?.role !== "user") continue;
+ messages[i] = withPart(messages[i], "check", note);
+ break;
+ }
+ }
+ }
+ };
- // Whenever the servers' heap cap is in the engine's env: the person's commands never get it.
- if (heap) hooks["shell.env"] = async (_info, output) => restoreShellEnv(env, output);
+ // Every shell call and terminal: the person's own NODE_OPTIONS (the language servers' heap cap stays
+ // the engine's), and none of this plugin's own variables.
+ hooks["shell.env"] = async (_info, output) => restoreShellEnv(env, output);
hooks.event = async ({ event } = {}) => {
const id = event?.properties?.sessionID;
diff --git a/apps/server/src/agent-assist/agent-assist.d.ts b/apps/server/src/agent-assist/agent-assist.d.ts
index c02dfc17..9c177253 100644
--- a/apps/server/src/agent-assist/agent-assist.d.ts
+++ b/apps/server/src/agent-assist/agent-assist.d.ts
@@ -11,7 +11,8 @@ export const LSP_BUILTIN_IDS: string[];
export const LSP_ENABLED_IDS: string[];
export const LSP_HEAP_MB: number;
export function lspConfig(): Record<string, { disabled: true }>;
-export function lspEngineEnv(env?: Record<string, string | undefined>): Record<string, string>;
+export function lspHeapMb(totalBytes?: number): number;
+export function lspEngineEnv(env?: Record<string, string | undefined>, options?: { totalBytes?: number }): Record<string, string>;
export function restoreShellEnv(processEnv: Record<string, string | undefined>, output: { env?: Record<string, string> } | undefined): void;
export function filterDiagnosticsOutput(text: string): { text: string; removed: number; kept: number };
export function capDiagnosticsMetadata<T>(map: T, options?: { files?: number; per?: number }): T;
@@ -24,6 +25,7 @@ export type CheckResult = { ok: boolean; passed: number | null; failed: number |
export function parseCheckResult(output: string, exitCode: number | null | undefined, command?: string): CheckResult;
export function isCodeEdit(tool: string, args: unknown): boolean;
export function skipRequested(text: string): boolean;
+export function declinesChange(text: string): boolean;
export const SELF_CHECK_ATTEMPTS: number;
export type CheckState = { edits: number; failures: number; ran: number; skip: boolean; last: CheckResult | null; shown: number };
export const SELF_CHECK_NOTE_REPEATS: number;
diff --git a/apps/server/src/agent-assist/agent-assist.js b/apps/server/src/agent-assist/agent-assist.js
index ed1a03d0..ba55a2f3 100644
--- a/apps/server/src/agent-assist/agent-assist.js
+++ b/apps/server/src/agent-assist/agent-assist.js
@@ -3,13 +3,14 @@
//
// PARITY: this file is the same in omnirush-cli
// (assets/extensions/omnirush/agent-assist/) and omnirush-gui
-// (apps/server/src/opencode-plugins/agent-assist/); PARITY.sha256 in both
+// (apps/server/src/agent-assist/); PARITY.sha256 in both
// lists its hash. Plain JavaScript on node built-ins only: the engine loads it
// as is (CLI) or bundled (desktop).
//
// Everything model-facing here is neutral wording; nothing names the app.
import fs from "node:fs";
+import os from "node:os";
import path from "node:path";
// --- feature switches ---------------------------------------------------------
@@ -85,8 +86,14 @@ export const LSP_BUILTIN_IDS = [
* for files the four already cover.
*/
export const LSP_ENABLED_IDS = ["typescript", "deno", "pyright", "gopls", "rust"];
-/** Heap cap (MB) for the Node-based servers (tsserver, pyright): VS Code's default for tsserver. */
+/** Heap cap (MB) for the Node-based servers (tsserver, pyright): VS Code's default for tsserver, at most a quarter of this machine's memory. */
export const LSP_HEAP_MB = 3072;
+const LSP_HEAP_MIN_MB = 768;
+
+export function lspHeapMb(totalBytes = os.totalmem()) {
+ const quarter = Math.floor(totalBytes / 4 / 1024 / 1024);
+ return Math.max(LSP_HEAP_MIN_MB, Math.min(LSP_HEAP_MB, quarter || LSP_HEAP_MB));
+}
/** The engine config's `lsp` value: every built-in server but the enabled ones turned off. */
export function lspConfig() {
@@ -99,15 +106,27 @@ export function lspConfig() {
* kept in OMNIRUSH_USER_NODE_OPTIONS and put back for every shell call and
* terminal (restoreShellEnv), so their commands run exactly as before.
*/
-export function lspEngineEnv(env = {}) {
+export function lspEngineEnv(env = {}, { totalBytes } = {}) {
+ const heap = lspHeapMb(totalBytes);
const own = typeof env.NODE_OPTIONS === "string" ? env.NODE_OPTIONS : "";
- const capped = /--max-old-space-size[= ]/.test(own) ? own : `${own} --max-old-space-size=${LSP_HEAP_MB}`.trim();
- return { NODE_OPTIONS: capped, OMNIRUSH_USER_NODE_OPTIONS: own, OMNIRUSH_LSP_HEAP: String(LSP_HEAP_MB) };
+ const capped = /--max-old-space-size[= ]/.test(own) ? own : `${own} --max-old-space-size=${heap}`.trim();
+ return { NODE_OPTIONS: capped, OMNIRUSH_USER_NODE_OPTIONS: own, OMNIRUSH_LSP_HEAP: String(heap) };
}
+/** The engine env this plugin adds; shell calls and terminals never see them. */
+const OWN_ENV = ["OMNIRUSH_AGENT_ASSIST", "OMNIRUSH_AGENT_ASSIST_DIR", "OMNIRUSH_AGENT_ASSIST_FILE", "OMNIRUSH_USER_NODE_OPTIONS", "OMNIRUSH_LSP_HEAP"];
+
+/**
+ * A shell call's or terminal's env (the engine's `shell.env` hook): the
+ * person's own NODE_OPTIONS back (empty when they had none), and this
+ * plugin's variables blanked.
+ */
export function restoreShellEnv(processEnv, output) {
- if (!output || !output.env || typeof processEnv.OMNIRUSH_LSP_HEAP !== "string") return;
- output.env.NODE_OPTIONS = typeof processEnv.OMNIRUSH_USER_NODE_OPTIONS === "string" ? processEnv.OMNIRUSH_USER_NODE_OPTIONS : "";
+ if (!output || !output.env) return;
+ if (typeof processEnv.OMNIRUSH_LSP_HEAP === "string") {
+ output.env.NODE_OPTIONS = typeof processEnv.OMNIRUSH_USER_NODE_OPTIONS === "string" ? processEnv.OMNIRUSH_USER_NODE_OPTIONS : "";
+ }
+ for (const name of OWN_ENV) if (typeof processEnv[name] === "string") output.env[name] = "";
}
const DIAG_BLOCK = /(\n*LSP errors detected in [^\n]*:\n)?<diagnostics file="([^"]*)">\n([\s\S]*?)\n<\/diagnostics>/g;
@@ -293,7 +312,7 @@ export function parseCheckResult(output, exitCode, command = "") {
failed = count(text, /^(?:# |ℹ )fail (\d+)/m) ?? 0;
}
if (passed === null) {
- const pytest = /=+ (?:(\d+) failed, )?(\d+) passed|=+ (\d+) failed/.exec(text);
+ const pytest = /^(?:=+ )?(?:(\d+) failed, )?(\d+) passed\b.* in [\d.]+s|^(?:=+ )?(\d+) failed\b.* in [\d.]+s/m.exec(text);
if (pytest) { failed = Number(pytest[1] ?? pytest[3] ?? 0); passed = Number(pytest[2] ?? 0); }
}
if (passed === null) {
@@ -310,7 +329,8 @@ export function parseCheckResult(output, exitCode, command = "") {
}
const tscErrors = count(text, /Found (\d+) errors?/);
const eslintProblems = count(text, /✖ (\d+) problems?/);
- const ok = exitCode === 0 || (exitCode === null || exitCode === undefined ? (failed === 0 && passed !== null) : false);
+ // A null exit is a call that timed out or was stopped: never a pass. Without any exit (no metadata) the counts decide.
+ const ok = exitCode === 0 || (exitCode === undefined ? (failed === 0 && passed !== null) : false);
const unit = /\bgo\s+test\b/.test(command) ? "packages" : "tests";
let summary;
if (passed !== null) {
@@ -347,9 +367,14 @@ export function isCodeEdit(tool, args) {
return files.length === 0 || files.some((file) => !NOT_CODE.test(file));
}
-/** Whether the person asked for no checks in this turn ("skip the tests", "don't run tests"). */
+/** Whether the person asked for no checks in this turn ("skip the tests", "don't run tests", "no need to run the checks"). */
export function skipRequested(text) {
- return /\b(?:skip|without|no need (?:to run|to|for)|don'?t run|do not run|no)\s+(?:running\s+)?(?:the\s+|any\s+)?(?:self[- ]?checks?|checks?|tests?|linters?|linting|type[- ]?checks?)\b/i.test(String(text || ""));
+ return /\b(?:skip(?:ping)?|don'?t run|do not run|no need to run|no need for|without running|never mind)\s+(?:the\s+|any\s+)?(?:self[- ]?checks?|checks?|tests?|test suite|linters?|linting|type[- ]?checks?)\b/i.test(String(text || ""));
+}
+
+/** Whether the person's answer to "apply this AGENTS.md change?" declines it. */
+export function declinesChange(text) {
+ return /^\s*(?:no\b|nope\b|nah\b|don'?t\b|do not\b|keep\b|leave\b|cancel\b|stop\b)/i.test(String(text || ""));
}
export const SELF_CHECK_ATTEMPTS = 3;
@@ -542,10 +567,13 @@ export function droppedLines(before, after) {
return dropped;
}
-function isNotesFile(file, root) {
+function isNotesFile(file, root, platform = process.platform) {
if (typeof file !== "string" || !file) return false;
- const full = path.resolve(root, file);
- return path.basename(full) === NOTES_FILE && (full === root || full.startsWith(root.endsWith(path.sep) ? root : root + path.sep));
+ // Case-insensitive file systems (Windows, macOS): agents.md is the same file.
+ const fold = platform === "win32" || platform === "darwin" ? (text) => text.toLowerCase() : (text) => text;
+ const full = fold(path.resolve(root, file));
+ const base = fold(path.resolve(root));
+ return path.basename(full).toLowerCase() === NOTES_FILE.toLowerCase() && full.startsWith(base.endsWith(path.sep) ? base : base + path.sep);
}
/**
@@ -612,7 +640,7 @@ export function notesGuardMessage(drops) {
// --- compaction -----------------------------------------------------------------
-const PREFERENCE = /^(?:keep|use|avoid|prefer|stick to|leave)\b|\b(?:always|never|don'?t|do not|please (?:use|keep|avoid|make)|prefer|make sure|must(?:n'?t)?|should(?:n'?t| not)?|from now on|instead of|avoid|only use|stick to)\b/i;
+const PREFERENCE = /^(?:keep|use|avoid|prefer|stick to|leave|never|always|don'?t|do not)\b|\b(?:always|never|please (?:use|keep|avoid|make|don'?t)|prefer|make sure|mustn'?t|must not|shouldn'?t|should not|from now on|instead of|only use|stick to)\b/i;
const DECISION = /\b(?:decided|we(?:'ll| will) (?:use|go with|keep)|going with|let'?s (?:use|go with|keep)|chose|switch(?:ed|ing)? to|the plan is)\b/i;
function sentences(text) {
@@ -648,7 +676,8 @@ export function sessionLedger(messages) {
for (const part of partsOf(message)) {
if (part?.type === "text" && !part.synthetic && !part.ignored && typeof part.text === "string") {
for (const sentence of sentences(part.text)) {
- if (role === "user" && PREFERENCE.test(sentence)) pushUnique(ledger.preferences, sentence, 12);
+ // A question is not a preference ("why should this fail?").
+ if (role === "user" && PREFERENCE.test(sentence) && !sentence.endsWith("?")) pushUnique(ledger.preferences, sentence, 12);
if (DECISION.test(sentence)) pushUnique(ledger.decisions, sentence, 10);
}
}
diff --git a/apps/server/src/embedded.ts b/apps/server/src/embedded.ts
index 0758423e..71ce08fe 100644
--- a/apps/server/src/embedded.ts
+++ b/apps/server/src/embedded.ts
@@ -5,7 +5,8 @@
* in one call -- mirrors what cli.ts does but returns a handle instead
* of owning the process lifecycle.
*/
-import { agentAssistEngineEnv } from "./agent-assist-config.js";
+import { agentAssistEngineEnv, agentAssistFlags } from "./agent-assist-config.js";
+import { readGlobalRuntimeOpencodeConfig } from "./runtime-opencode-config-store.js";
import { randomUUID } from "node:crypto";
import { stopTaskRecovery } from "./task-recovery.js";
import { managedDesktopPolicy } from "./managed-desktop-policy.js";
@@ -278,7 +279,7 @@ export async function startEmbeddedServer(options: EmbeddedServerOptions): Promi
...opencodeModelsEnv,
...pluginsNoDepsEnv(omnirushOwnPluginPaths()),
// Agent assist: the plugin's switch file and notes folder, the language servers' heap cap.
- ...agentAssistEngineEnv(config),
+ ...agentAssistEngineEnv(config, process.env, { diagnostics: agentAssistFlags(await readGlobalRuntimeOpencodeConfig(config)).diagnostics }),
};
engineSpawnTemplate = {
bin: opencodeBin,