A desktop coding agent with free access to frontier models.
TypeScript
feat: agent self-check, project notes and diagnostics
ogsamrat50e4be2fabbf
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.tsindex 58a778f0..a0a30984 100644--- a/apps/app/src/app/lib/omnirush-server.ts+++ b/apps/app/src/app/lib/omnirush-server.ts@@ -424,6 +424,18 @@ export type OmniRushCaptureStatus = {since: string | null;restarts: number;};+/** Agent assist (apps/server/src/agent-assist-config.ts): what the agent does on its own; all on by default. */+export type OmniRushAgentAssistFeature = "selfCheck" | "projectNotes" | "diagnostics" | "compaction";+export type OmniRushAgentAssist = {+ features: Record<OmniRushAgentAssistFeature, boolean>;+ /** Decided by an environment switch of the server (shown, not changeable). */+ forced: OmniRushAgentAssistFeature[];+};+export type OmniRushAgentAssistChange = OmniRushAgentAssist & {+ ok: boolean;+ changed: boolean;+ engine: { status: "applied" | "deferred" | "failed" | "unconfigured" };+};export type OmniRushBestPracticesChange = OmniRushBestPractices & {ok: boolean;changed: boolean;@@ -2014,6 +2026,16 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: srequestJson<{ ok: boolean; projects: number; box: string }>(baseUrl, "/runtime-config/buildathon", {token, hostToken, method: "PUT", body, timeoutMs: ENGINE_RELOAD_TIMEOUT_MS,}),+ getAgentAssist: () =>+ requestJson<OmniRushAgentAssist>(baseUrl, "/runtime-config/agent-assist", { token, hostToken, timeoutMs: timeouts.config }),+ setAgentAssist: (change: Partial<Record<OmniRushAgentAssistFeature, boolean>>) =>+ requestJson<OmniRushAgentAssistChange>(baseUrl, "/runtime-config/agent-assist", {+ token,+ hostToken,+ method: "PUT",+ body: change,+ timeoutMs: ENGINE_RELOAD_TIMEOUT_MS,+ }),getBestPractices: () =>requestJson<OmniRushBestPractices>(baseUrl, "/runtime-config/best-practices", { token, hostToken, timeoutMs: timeouts.config }),setBestPractices: (enabled: boolean) =>diff --git a/apps/app/src/react-app/domains/session/sync/agent-assist-toast.ts b/apps/app/src/react-app/domains/session/sync/agent-assist-toast.tsnew file mode 100644index 00000000..6dd50fd5--- /dev/null+++ b/apps/app/src/react-app/domains/session/sync/agent-assist-toast.ts@@ -0,0 +1,37 @@+import { toast } from "@/components/ui/sonner";++/**+ * The engine's agent assist plugin (apps/server/src/agent-assist/) reports+ * through the engine's toast event: "Checked: 42 tests passed", "Check+ * failed", "Not checked", "Project notes". The app shows those, and only those+ * (NOTICE_TITLES in agent-assist.js; agent-assist-toast.test.ts keeps the list+ * equal), as its own toasts. One toast reaches every workspace stream of the+ * engine, so a repeat within a few seconds is dropped.+ */+export const AGENT_ASSIST_TOAST_TITLES = ["Checked", "Check failed", "Not checked", "Project notes"];+const REPEAT_MS = 3_000;+let last = { key: "", at: 0 };++export function agentAssistToast(properties: unknown, now = Date.now()): { title: string; message: string; variant: string } | null {+ if (!properties || typeof properties !== "object") return null;+ const { title, message, variant } = properties as Record<string, unknown>;+ if (typeof title !== "string" || !AGENT_ASSIST_TOAST_TITLES.includes(title) || typeof message !== "string") return null;+ const key = `${title}\n${message}`;+ if (last.key === key && now - last.at < REPEAT_MS) return null;+ last = { key, at: now };+ return { title, message, variant: typeof variant === "string" ? variant : "info" };+}++/** Shows an agent assist toast from an engine event; whether the event was one. */+export function showAgentAssistToast(event: { type: string; properties?: unknown }): boolean {+ if (event.type !== "tui.toast.show") return false;+ const shown = agentAssistToast(event.properties);+ if (!shown) return true;+ const text = shown.title === "Checked" || shown.title === "Check failed" ? `${shown.title}: ${shown.message}` : shown.title;+ const options = shown.title === "Checked" || shown.title === "Check failed" ? { duration: 6_000 } : { description: shown.message.replace(/`/g, ""), duration: 10_000 };+ if (shown.variant === "success") toast.success(text, options);+ else if (shown.variant === "warning") toast.warning(text, options);+ else if (shown.variant === "error") toast.error(text, options);+ else toast.info(text, options);+ return true;+}diff --git a/apps/app/src/react-app/domains/session/sync/session-sync.ts b/apps/app/src/react-app/domains/session/sync/session-sync.tsindex 5b914729..014c04c0 100644--- a/apps/app/src/react-app/domains/session/sync/session-sync.ts+++ b/apps/app/src/react-app/domains/session/sync/session-sync.ts@@ -1,3 +1,4 @@+import { showAgentAssistToast } from "./agent-assist-toast";import type { UIMessage } from "ai";import { create } from "zustand";import type { FilePart, Part, PermissionRequest, PermissionV2Request, QuestionRequest, Session, SessionStatus, Todo } from "@opencode-ai/sdk/v2/client";@@ -847,6 +848,8 @@ function upsertPart(messages: UIMessage[], messageId: string, partId: string, ne}function applyEvent(entry: SyncEntry, workspaceId: string, event: OpencodeEvent) {+ // The engine's toasts: the agent assist plugin's notices (checks, project notes).+ if (showAgentAssistToast(event as { type: string; properties?: unknown })) return;observeModelsTaskEvent(workspaceId, event);const queryClient = getReactQueryClient();const input = entry.input;diff --git a/apps/app/src/react-app/domains/settings/agent-assist.ts b/apps/app/src/react-app/domains/settings/agent-assist.tsnew file mode 100644index 00000000..98c5e32b--- /dev/null+++ b/apps/app/src/react-app/domains/settings/agent-assist.ts@@ -0,0 +1,93 @@+import { useCallback, useEffect, useRef, useState } from "react";++import type { OmniRushAgentAssist, OmniRushAgentAssistChange, OmniRushAgentAssistFeature, OmniRushServerClient } from "@/app/lib/omnirush-server";++export type AgentAssistClient = Pick<OmniRushServerClient, "getAgentAssist" | "setAgentAssist">;++/** Settings > General > Agent: the four switches, in order, with their help lines. */+export const AGENT_ASSIST_ITEMS: { key: OmniRushAgentAssistFeature; title: string; help: string }[] = [+ {+ key: "selfCheck",+ title: "Check work before finishing",+ help: "After changing code, the agent runs the project's tests, linter or type check and fixes what fails (at most 3 rounds). Say \"skip the tests\" to skip it once.",+ },+ {+ key: "projectNotes",+ title: "Project notes (AGENTS.md)",+ help: "/init writes AGENTS.md with the build, test and run commands and conventions; the app offers to add what a session found. Your own lines are never removed without asking.",+ },+ {+ key: "diagnostics",+ title: "Code diagnostics",+ help: "Language servers for TypeScript/JavaScript, Python, Go and Rust tell the agent about errors right after each edit.",+ },+ {+ key: "compaction",+ title: "Detailed summaries",+ help: "When a long chat is summarized, keep your preferences, decisions, open to-dos, commands that worked and the files changed.",+ },+];++export function agentAssistChangeMessage(result: OmniRushAgentAssistChange): string {+ switch (result.engine.status) {+ case "applied":+ return "Saved. Applies to the next request.";+ case "deferred":+ return "Saved. Code diagnostics change once the engine is idle.";+ case "failed":+ return "Saved. The engine change could not be confirmed. Use Reload in Settings to apply it.";+ case "unconfigured":+ return "Saved. Applies when the engine starts.";+ }+}++export function useAgentAssist(client: AgentAssistClient | null) {+ const [setting, setSetting] = useState<OmniRushAgentAssist | null>(null);+ const [busy, setBusy] = useState(false);+ const [status, setStatus] = useState("");+ // A GET begun before a PUT must not replace the newly saved choice.+ const sequence = useRef(0);++ useEffect(() => {+ sequence.current += 1;+ const startedAt = sequence.current;+ let cancelled = false;+ setSetting(null);+ setBusy(false);+ setStatus("");+ if (client) {+ void client.getAgentAssist()+ .then((value) => {+ if (!cancelled && sequence.current === startedAt) setSetting(value);+ })+ .catch(() => {+ if (!cancelled && sequence.current === startedAt) setStatus("Agent settings could not be loaded. Try opening Settings again.");+ });+ }+ return () => { cancelled = true; };+ }, [client]);++ const setFeature = useCallback(async (key: OmniRushAgentAssistFeature, enabled: boolean) => {+ if (!client || busy) return;+ sequence.current += 1;+ const startedAt = sequence.current;+ setBusy(true);+ setStatus("Saving…");+ try {+ const result = await client.setAgentAssist({ [key]: enabled });+ if (sequence.current !== startedAt) return;+ setSetting({ features: result.features, forced: result.forced });+ setStatus(agentAssistChangeMessage(result));+ } catch {+ if (sequence.current !== startedAt) return;+ const saved = await client.getAgentAssist().catch(() => null);+ if (sequence.current !== startedAt) return;+ if (saved) setSetting(saved);+ setStatus("The change could not be saved. Open Settings again to check it.");+ } finally {+ if (sequence.current === startedAt) setBusy(false);+ }+ }, [busy, client]);++ return { setting, busy, status, setFeature };+}diff --git a/apps/app/src/react-app/domains/settings/pages/general-view.tsx b/apps/app/src/react-app/domains/settings/pages/general-view.tsxindex abb933eb..c7e9f645 100644--- a/apps/app/src/react-app/domains/settings/pages/general-view.tsx+++ b/apps/app/src/react-app/domains/settings/pages/general-view.tsx@@ -2,6 +2,7 @@import { useEffect, useState } from "react";import {ArrowRight,+ Bot,Coffee,Cog,FolderLock,@@ -40,6 +41,8 @@ import {import { DiagnosticsSection } from "./diagnostics-section";import { keptPendingLine, sendPendingBeforeSignOut } from "../sign-out-uploads";import { BEST_PRACTICES_HELP, useBestPractices, type BestPracticesClient } from "../best-practices";+import { AGENT_ASSIST_ITEMS, useAgentAssist, type AgentAssistClient } from "../agent-assist";+import type { OmniRushAgentAssist, OmniRushAgentAssistFeature } from "../../../../app/lib/omnirush-server";import { useLinuxSandbox, type LinuxSandboxClient } from "../linux-sandbox";import { LinuxSandboxCard } from "../linux-sandbox-card";import { BuildathonTrackCard } from "../../buildathon/buildathon";@@ -51,6 +54,8 @@ export type GeneralSettingsViewProps = {omnirushClient?: ApprovalsClient | null;/** Global guides do not depend on workspace selection or history loading. */bestPracticesClient?: BestPracticesClient | null;+ /** Agent assist switches (self-check, project notes, diagnostics, summaries); hidden without one. */+ agentAssistClient?: AgentAssistClient | null;/** Workspace whose engine is reloaded after the approval mode changes. */runtimeWorkspaceId?: string | null;/** The Linux sandbox card (per project); hidden without a client or a selected workspace. */@@ -224,6 +229,53 @@ export function BestPracticesCard(props: {);}+/** Settings > General > Agent: what the agent does on its own (agent-assist-config.ts on the server). */+export function AgentAssistCard(props: {+ setting: OmniRushAgentAssist | null;+ busy: boolean;+ status: string;+ onToggle: (key: OmniRushAgentAssistFeature, enabled: boolean) => void;+}) {+ return (+ <div className="space-y-3">+ <div className="text-[11px] font-semibold uppercase tracking-[0.15em] text-dls-secondary">Agent</div>+ <div className="rounded-2xl border border-dls-border bg-dls-surface" data-testid="agent-assist-card">+ {AGENT_ASSIST_ITEMS.map((item, index) => {+ const forced = props.setting?.forced.includes(item.key) ?? false;+ return (+ <div key={item.key} className={`flex items-center gap-4 p-4${index > 0 ? " border-t border-dls-border" : ""}`}>+ {index === 0 ? (+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-dls-border bg-dls-hover">+ <Bot size={17} className="text-dls-secondary" />+ </div>+ ) : (+ <div className="h-10 w-10 shrink-0" aria-hidden="true" />+ )}+ <div className="min-w-0 flex-1">+ <div className="text-[13px] font-medium text-dls-text">{item.title}</div>+ <div id={`agent-assist-${item.key}-help`} className="text-[11px] text-dls-secondary">+ {item.help}+ {forced ? " Set by the app's environment." : ""}+ </div>+ </div>+ <Switch+ aria-label={item.title}+ aria-describedby={`agent-assist-${item.key}-help`}+ checked={props.setting?.features[item.key] === true}+ disabled={props.busy || props.setting === null || forced}+ onCheckedChange={(enabled) => props.onToggle(item.key, enabled)}+ />+ </div>+ );+ })}+ </div>+ {props.status ? (+ <div className="text-[11px] text-dls-secondary" role="status" data-testid="agent-assist-status">{props.status}</div>+ ) : null}+ </div>+ );+}+export const KEEP_AWAKE_TITLE = "Keep this computer awake while the agent works";export const KEEP_AWAKE_HELP = "Your computer won't go to sleep while a turn runs, or while the app finishes up as it quits. The screen can still turn off and lock.";@@ -292,6 +344,8 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {const approvalMode = useApprovalMode(approvalsClient, props.runtimeWorkspaceId ?? null);const bestPracticesClient = props.bestPracticesClient ?? null;const bestPractices = useBestPractices(bestPracticesClient);+ const agentAssistClient = props.agentAssistClient ?? null;+ const agentAssist = useAgentAssist(agentAssistClient);const linuxSandboxClient = props.linuxSandboxClient ?? null;const linuxSandbox = useLinuxSandbox(linuxSandboxClient, props.sandboxWorkspaceId ?? null);const keepAwake = useKeepAwake();@@ -464,6 +518,15 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {/>) : null}+ {agentAssistClient ? (+ <AgentAssistCard+ setting={agentAssist.setting}+ busy={agentAssist.busy}+ status={agentAssist.status}+ onToggle={(key, enabled) => void agentAssist.setFeature(key, enabled)}+ />+ ) : null}+{isElectronRuntime() ? (<KeepAwakeCardstate={keepAwake.state}diff --git a/apps/app/src/react-app/shell/settings-route.tsx b/apps/app/src/react-app/shell/settings-route.tsxindex e2f537da..5e3fea7d 100644--- a/apps/app/src/react-app/shell/settings-route.tsx+++ b/apps/app/src/react-app/shell/settings-route.tsx@@ -86,6 +86,7 @@ import { isOmniRushExtensionEnabled, OMNIRUSH_EXTENSION_STATE_CHANGED } from "@/import { PreferencesView } from "@/react-app/domains/settings/pages/preferences-view";import { GeneralSettingsView } from "@/react-app/domains/settings/pages/general-view";import type { BestPracticesClient } from "@/react-app/domains/settings/best-practices";+import type { AgentAssistClient } from "@/react-app/domains/settings/agent-assist";import { AuthorizedFoldersPanel } from "@/react-app/domains/settings/panels/authorized-folders-panel";import { BrowserLoginsPanel } from "../domains/browser-logins/browser-logins-panel";import { EffectivePermissionsPanel } from "@/react-app/domains/settings/panels/effective-permissions-panel";@@ -514,7 +515,7 @@ function SettingsRouteContent(props: SettingsSurfaceProps = {}) {const [baseUrl, setBaseUrl] = useState("");const [token, setToken] = useState("");const [omnirushClient, setOmniRushClient] = useState<OmniRushServerClient | null>(null);- const [bestPracticesClient, setBestPracticesClient] = useState<BestPracticesClient | null>(null);+ const [bestPracticesClient, setBestPracticesClient] = useState<(BestPracticesClient & AgentAssistClient) | null>(null);const [activeClient, setActiveClient] = useState<Client | null>(null);const [busy, setBusy] = useState(false);const [busyLabel, setBusyLabel] = useState<string | null>(null);@@ -2285,6 +2286,7 @@ function SettingsRouteContent(props: SettingsSurfaceProps = {}) {developerMode={developerMode}omnirushClient={omnirushClient}bestPracticesClient={bestPracticesClient}+ agentAssistClient={bestPracticesClient}runtimeWorkspaceId={runtimeWorkspaceId}linuxSandboxClient={omnirushClient}sandboxWorkspaceId={selectedWorkspaceId || runtimeWorkspaceId}diff --git a/apps/app/tests/agent-assist-toast.test.ts b/apps/app/tests/agent-assist-toast.test.tsnew file mode 100644index 00000000..eb3098a3--- /dev/null+++ b/apps/app/tests/agent-assist-toast.test.ts@@ -0,0 +1,14 @@+import { expect, test } from "bun:test";++import { NOTICE_TITLES } from "../../server/src/agent-assist/agent-assist.js";+import { AGENT_ASSIST_TOAST_TITLES, agentAssistToast } from "../src/react-app/domains/session/sync/agent-assist-toast";++test("the app shows the agent assist plugin's toasts, and only those", () => {+ expect(AGENT_ASSIST_TOAST_TITLES).toEqual(NOTICE_TITLES);+ expect(agentAssistToast({ title: "Checked", message: "42 tests passed", variant: "success" }, 1_000)).toEqual({ title: "Checked", message: "42 tests passed", variant: "success" });+ // The same toast from a second workspace stream is dropped.+ expect(agentAssistToast({ title: "Checked", message: "42 tests passed", variant: "success" }, 1_500)).toBeNull();+ expect(agentAssistToast({ title: "Checked", message: "42 tests passed", variant: "success" }, 9_000)).not.toBeNull();+ expect(agentAssistToast({ title: "Some engine toast", message: "x" }, 20_000)).toBeNull();+ expect(agentAssistToast(null)).toBeNull();+});diff --git a/apps/server/package.json b/apps/server/package.jsonindex 9a7f48b5..befc2af0 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -12,7 +12,7 @@"test:coverage": "bun --conditions=development test --coverage --coverage-reporter=text --coverage-reporter=lcov --coverage-dir=coverage","test:artifacts": "bun --conditions=development test src/artifact-files.e2e.test.ts src/workspace-init.test.ts src/server.normalizeWorkspaceRelativePath.test.ts","build:enterprise-mcp-client": "pnpm --filter @omnirush/enterprise-mcp-client build",- "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts src/opencode-plugins/omnirush-reasoning-effort.ts src/opencode-plugins/omnirush-swarm.ts src/opencode-plugins/omnirush-budget-wrap.ts src/opencode-plugins/omnirush-mcp-policy.ts src/opencode-plugins/omnirush-box.ts src/opencode-plugins/omnirush-buildathon.ts --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins",+ "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts src/opencode-plugins/omnirush-reasoning-effort.ts src/opencode-plugins/omnirush-swarm.ts src/opencode-plugins/omnirush-budget-wrap.ts src/opencode-plugins/omnirush-mcp-policy.ts src/opencode-plugins/omnirush-box.ts src/opencode-plugins/omnirush-buildathon.ts src/opencode-plugins/omnirush-agent-assist.ts --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins","build:bin": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun build --compile src/cli.ts --outfile dist/bin/omnirush-server","build:bin:all": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun ./script/build.ts --outdir dist/bin --target bun-darwin-arm64 --target bun-darwin-x64 --target bun-linux-x64 --target bun-linux-arm64 --target bun-windows-x64 --target bun-windows-arm64","prepare:npm": "pnpm build:bin && node scripts/publish-npm.mjs --prepare-only",diff --git a/apps/server/src/agent-assist-config.test.ts b/apps/server/src/agent-assist-config.test.tsnew file mode 100644index 00000000..8ab58532--- /dev/null+++ b/apps/server/src/agent-assist-config.test.ts@@ -0,0 +1,84 @@+import { describe, expect, test } from "bun:test";+import { createHash } from "node:crypto";+import { readFileSync } from "node:fs";+import { mkdtemp, readFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++import * as shared from "./agent-assist/agent-assist.js";+import { agentAssistHooks } from "./agent-assist/agent-assist-hooks.js";+import {+ AGENT_ASSIST_FEATURES,+ LSP_BUILTIN_IDS,+ LSP_ENABLED_IDS,+ LSP_HEAP_MB,+ agentAssistEngineEnv,+ agentAssistFlags,+ agentAssistForced,+ agentAssistLspConfig,+ normalizeAgentAssistSetting,+ writeAgentAssistFile,+} from "./agent-assist-config.js";+import { buildOmniRushRuntimeConfigObjectFromSnapshot, omnirushOwnPluginPaths } from "./omnirush-runtime-config.js";+import type { ServerConfig } from "./types.js";++const here = dirname(fileURLToPath(import.meta.url));++describe("agent assist", () => {+ test("CLI/desktop parity: agent-assist/PARITY.sha256 matches its files", () => {+ const dir = join(here, "agent-assist");+ const rows = readFileSync(join(dir, "PARITY.sha256"), "utf8").split("\n").filter((line) => line && !line.startsWith("#"));+ expect(rows.length).toBe(2);+ for (const row of rows) {+ const [hash, name] = row.split(/\s+/);+ expect(createHash("sha256").update(readFileSync(join(dir, name!))).digest("hex")).toBe(hash!);+ }+ });++ test("the server's copies of the shared values match agent-assist.js", () => {+ expect([...AGENT_ASSIST_FEATURES]).toEqual(shared.FEATURES);+ expect(LSP_BUILTIN_IDS).toEqual(shared.LSP_BUILTIN_IDS);+ expect(LSP_ENABLED_IDS).toEqual(shared.LSP_ENABLED_IDS);+ expect(LSP_HEAP_MB).toBe(shared.LSP_HEAP_MB);+ expect(agentAssistLspConfig()).toEqual(shared.lspConfig());+ for (const env of [{}, { OMNIRUSH_SELF_CHECK: "0" }, { OMNIRUSH_CODE_DIAGNOSTICS: "off", OMNIRUSH_SMART_COMPACTION: "1" }]) {+ for (const saved of [undefined, { compaction: false }, { selfCheck: false, diagnostics: true }]) {+ expect(agentAssistFlags({ agentAssist: saved }, env)).toEqual(shared.featureFlags({ env, settings: { agentAssist: saved } }));+ }+ }+ const config = { configPath: "/data/server.json" } as unknown as ServerConfig;+ const env = agentAssistEngineEnv(config, { NODE_OPTIONS: "--trace-warnings" });+ 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);+ });++ test("the saved setting keeps booleans only; env switches are reported as forced", () => {+ expect(normalizeAgentAssistSetting({ selfCheck: false, other: false, compaction: "no" })).toEqual({ selfCheck: false });+ expect(normalizeAgentAssistSetting({})).toBeUndefined();+ expect(agentAssistForced({ OMNIRUSH_PROJECT_NOTES: "0" })).toEqual(["projectNotes"]);+ });++ test("engine config: the plugin always (inert while off), the language servers only while diagnostics are on", () => {+ const on = buildOmniRushRuntimeConfigObjectFromSnapshot({}, undefined, {});+ expect((on.plugin as string[]).some((entry) => /omnirush-agent-assist\.(?:js|ts)$/.test(entry))).toBe(true);+ expect(on.lsp).toEqual(agentAssistLspConfig());+ expect(omnirushOwnPluginPaths().some((entry) => /omnirush-agent-assist\.(?:js|ts)$/.test(entry))).toBe(true);+ const off = buildOmniRushRuntimeConfigObjectFromSnapshot({ agentAssist: { diagnostics: false } }, undefined, {});+ expect(off.lsp).toBeUndefined();+ expect(off.agentAssist).toBeUndefined();+ expect(buildOmniRushRuntimeConfigObjectFromSnapshot({}, undefined, { OMNIRUSH_CODE_DIAGNOSTICS: "0" }).lsp).toBeUndefined();+ });++ test("the switch file is what the plugin reads", async () => {+ const dir = await mkdtemp(join(tmpdir(), "agent-assist-"));+ const config = { configPath: join(dir, "server.json") } as unknown as ServerConfig;+ const flags = { selfCheck: true, projectNotes: false, diagnostics: true, compaction: false };+ expect(await writeAgentAssistFile(config, flags)).toBe(true);+ expect(await writeAgentAssistFile(config, flags)).toBe(false);+ const env = agentAssistEngineEnv(config, {});+ expect(JSON.parse(await readFile(env.OMNIRUSH_AGENT_ASSIST_FILE!, "utf8"))).toEqual({ features: ["selfCheck", "diagnostics"] });+ expect(shared.featuresFromEnv(env)).toEqual(flags);+ expect(Object.keys(agentAssistHooks({ directory: dir }, { env }))).toContain("experimental.chat.system.transform");+ });+});diff --git a/apps/server/src/agent-assist-config.ts b/apps/server/src/agent-assist-config.tsnew file mode 100644index 00000000..64c68ade--- /dev/null+++ b/apps/server/src/agent-assist-config.ts@@ -0,0 +1,115 @@+/**+ * Agent assist in the desktop app: which features are on and what they add to+ * the engine. The features live in the engine plugin+ * (opencode-plugins/omnirush-agent-assist.ts and the shared agent-assist/+ * modules, the same files as the CLI's):+ *+ * selfCheck after code edits the agent runs the project's checks and fixes failures+ * projectNotes /init writes AGENTS.md from the repository's facts; never drops the+ * person's lines without a diff and a yes+ * diagnostics language servers (TS/JS, Python, Go, Rust) report errors after edits+ * compaction summaries keep preferences, decisions, to-dos, commands, file state+ *+ * All on by default; Settings > General > Agent saves `agentAssist` in the+ * engine-global runtime config. OMNIRUSH_SELF_CHECK, OMNIRUSH_PROJECT_NOTES,+ * OMNIRUSH_CODE_DIAGNOSTICS and OMNIRUSH_SMART_COMPACTION (0/1) in the server's+ * environment win. The plugin reads the features from a small file the server+ * rewrites on every change, so a switch applies at the next model call.+ *+ * The values below mirror agent-assist/agent-assist.js (that file is not part+ * of the server's build output); agent-assist-config.test.ts keeps them equal.+ */+import { mkdir, readFile } from "node:fs/promises";+import { join } from "node:path";++import { writeFileAtomic } from "./atomic-write.js";+import { runtimeStorageDir } from "./runtime-db.js";+import type { RuntimeOpencodeConfig } from "./runtime-opencode-config-store.js";+import type { ServerConfig } from "./types.js";++export const AGENT_ASSIST_FEATURES = ["selfCheck", "projectNotes", "diagnostics", "compaction"] as const;+export type AgentAssistFeature = (typeof AGENT_ASSIST_FEATURES)[number];+export type AgentAssistFlags = Record<AgentAssistFeature, boolean>;+export type AgentAssistSetting = Partial<Record<AgentAssistFeature, boolean>>;++const ENV_SWITCH: Record<AgentAssistFeature, string> = {+ selfCheck: "OMNIRUSH_SELF_CHECK",+ projectNotes: "OMNIRUSH_PROJECT_NOTES",+ diagnostics: "OMNIRUSH_CODE_DIAGNOSTICS",+ compaction: "OMNIRUSH_SMART_COMPACTION",+};++/** The engine's built-in language servers; all but LSP_ENABLED_IDS are turned off. */+export const LSP_BUILTIN_IDS = [+ "deno", "typescript", "vue", "eslint", "oxlint", "biome", "gopls", "ruby-lsp", "ty", "pyright",+ "elixir-ls", "zls", "csharp", "razor", "fsharp", "sourcekit-lsp", "rust", "clangd", "svelte", "astro",+ "jdtls", "kotlin-ls", "yaml-ls", "lua-ls", "php intelephense", "prisma", "dart", "ocaml-lsp", "bash",+ "terraform", "texlab", "dockerfile", "gleam", "clojure-lsp", "nixd", "tinymist", "haskell-language-server", "julials",+];+export const LSP_ENABLED_IDS = ["typescript", "deno", "pyright", "gopls", "rust"];+export const LSP_HEAP_MB = 3072;++function switchValue(value: string | undefined): boolean | null {+ const text = String(value ?? "").trim().toLowerCase();+ if (["0", "off", "false", "no"].includes(text)) return false;+ if (["1", "on", "true", "yes"].includes(text)) return true;+ return null;+}++/** The saved choice (absent features are on). */+export function normalizeAgentAssistSetting(value: unknown): AgentAssistSetting | undefined {+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;+ const out: AgentAssistSetting = {};+ for (const key of AGENT_ASSIST_FEATURES) {+ const entry = (value as Record<string, unknown>)[key];+ if (typeof entry === "boolean") out[key] = entry;+ }+ return Object.keys(out).length ? out : undefined;+}++/** The features on: a server env switch wins, then the saved setting, else on. */+export function agentAssistFlags(runtime: Pick<RuntimeOpencodeConfig, "agentAssist">, env: NodeJS.ProcessEnv = process.env): AgentAssistFlags {+ const saved = runtime.agentAssist ?? {};+ return Object.fromEntries(AGENT_ASSIST_FEATURES.map((key) => [key, switchValue(env[ENV_SWITCH[key]]) ?? saved[key] !== false])) as AgentAssistFlags;+}++/** Which features a server env switch decides (Settings shows them as fixed). */+export function agentAssistForced(env: NodeJS.ProcessEnv = process.env): AgentAssistFeature[] {+ return AGENT_ASSIST_FEATURES.filter((key) => switchValue(env[ENV_SWITCH[key]]) !== null);+}++/** The engine config's `lsp` value while diagnostics are on. */+export function agentAssistLspConfig(): Record<string, { disabled: true }> {+ return Object.fromEntries(LSP_BUILTIN_IDS.filter((id) => !LSP_ENABLED_IDS.includes(id)).map((id) => [id, { disabled: true as const }]));+}++export function agentAssistFilePath(config: ServerConfig): string {+ return join(runtimeStorageDir(config), "agent-assist.json");+}++/**+ * 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).+ */+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 {+ 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),+ };+}++/** Rewrites the plugin's switch file when the features changed. */+export async function writeAgentAssistFile(config: ServerConfig, flags: AgentAssistFlags): Promise<boolean> {+ const path = agentAssistFilePath(config);+ const content = `${JSON.stringify({ features: AGENT_ASSIST_FEATURES.filter((key) => flags[key]) })}\n`;+ if ((await readFile(path, "utf8").catch(() => undefined)) === content) return false;+ await mkdir(runtimeStorageDir(config), { recursive: true });+ await writeFileAtomic(path, content);+ return true;+}diff --git a/apps/server/src/agent-assist/PARITY.sha256 b/apps/server/src/agent-assist/PARITY.sha256new file mode 100644index 00000000..b418ebe8--- /dev/null+++ b/apps/server/src/agent-assist/PARITY.sha256@@ -0,0 +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.jsdiff --git a/apps/server/src/agent-assist/agent-assist-hooks.d.ts b/apps/server/src/agent-assist/agent-assist-hooks.d.tsnew file mode 100644index 00000000..bd44cbc9--- /dev/null+++ b/apps/server/src/agent-assist/agent-assist-hooks.d.ts@@ -0,0 +1,5 @@+// Types for agent-assist-hooks.js (shared with omnirush-cli; see PARITY.sha256).+export function agentAssistHooks(+ input?: { client?: unknown; directory?: string; worktree?: string },+ options?: { env?: Record<string, string | undefined>; now?: () => number; log?: (level: string, message: string, extra?: unknown) => void },+): Record<string, (...args: any[]) => Promise<void>>;diff --git a/apps/server/src/agent-assist/agent-assist-hooks.js b/apps/server/src/agent-assist/agent-assist-hooks.jsnew file mode 100644index 00000000..b13dab43--- /dev/null+++ b/apps/server/src/agent-assist/agent-assist-hooks.js@@ -0,0 +1,283 @@+// Engine plugin hooks for agent assist (agent-assist.js). PARITY: the same file+// 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".+// - 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.+// - 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).++import fs from "node:fs";+import os from "node:os";+import path from "node:path";++import {+ FEATURES_FILE_ENV,+ compactionContext,+ detectChecks,+ devCommand,+ featuresFromEnv,+ filterDiagnosticsOutput,+ capDiagnosticsMetadata,+ isCheckCommand,+ isCodeEdit,+ admitNote,+ latestSummary,+ learnedCommands,+ missingFactsNote,+ newCheckState,+ noteCheckRun,+ noteEdit,+ notesGuardMessage,+ notesLinesDropped,+ noteUserPrompt,+ parseCheckResult,+ projectScan,+ restoreShellEnv,+ selfCheckNote,+ sessionLedger,+} from "./agent-assist.js";++const FILE_TOOLS = new Set(["edit", "write", "apply_patch", "multiedit", "patch"]);+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;++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;+}++export function agentAssistHooks(input = {}, { env = process.env, now = () => Date.now(), log = () => undefined } = {}) {+ // The switches can change while the engine runs (the desktop app rewrites its+ // file): read at most every few seconds; every hook checks them.+ let flagsCache = { at: -Infinity, value: featuresFromEnv(env) };+ const flags = () => {+ if (now() - flagsCache.at > FLAGS_TTL_MS) flagsCache = { at: now(), value: featuresFromEnv(env) };+ 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 {};+ const root = path.resolve(input.directory || input.worktree || process.cwd());+ const client = input.client;+ const sessions = new Map();+ const ledgers = new Map();+ let checksCache = { at: -Infinity, list: [] };++ const checks = () => {+ if (now() - checksCache.at > CHECKS_TTL_MS) checksCache = { at: now(), list: detectChecks(root) };+ return checksCache.list;+ };+ const session = (id) => {+ let st = sessions.get(id);+ if (!st) {+ st = { check: newCheckState(), compactingSince: 0, notesBlocked: false, notesAllowed: false, worked: [], offered: new Set() };+ sessions.set(id, st);+ }+ return st;+ };+ 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 } });+ 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) => {+ try {+ if (on) {+ fs.mkdirSync(ledgerDir(env), { recursive: true, mode: 0o700 });+ fs.writeFileSync(pendingFile(id), "", { mode: 0o600 });+ } else fs.rmSync(pendingFile(id), { force: true });+ } catch { /* memory only */ }+ };+ const pending = (id) => {+ try { return fs.existsSync(pendingFile(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 */ }+ };+ const loadLedger = (id) => {+ if (ledgers.has(id)) return ledgers.get(id);+ try {+ const entry = JSON.parse(fs.readFileSync(ledgerFile(id), "utf8"));+ ledgers.set(id, entry);+ return entry;+ } catch {+ return null;+ }+ };+ const sessionMessages = async (id) => {+ try {+ const response = await client?.session?.messages?.({ path: { id }, query: { directory: root } });+ return Array.isArray(response?.data) ? response.data : [];+ } catch (error) {+ log("warn", "agent assist: messages unavailable", { error: error instanceof Error ? error.message : String(error) });+ return [];+ }+ };++ const hooks = {};++ hooks["chat.message"] = async (info, output) => {+ if (!info?.sessionID) return;+ const text = promptText(output?.parts);+ 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);+ 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["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;+ const tool = String(info.tool || "").toLowerCase();+ const on = flags();+ const st = session(info.sessionID);+ if (FILE_TOOLS.has(tool)) {+ if (on.diagnostics) {+ const filtered = filterDiagnosticsOutput(output.output);+ if (filtered.removed > 0) output.output = filtered.text;+ // apply_patch repeats its output as the title.+ if (typeof output.title === "string" && output.title.includes("<diagnostics")) output.title = filterDiagnosticsOutput(output.title).text;+ if (output.metadata && typeof output.metadata === "object" && output.metadata.diagnostics) {+ output.metadata.diagnostics = capDiagnosticsMetadata(output.metadata.diagnostics);+ }+ }+ if (on.selfCheck && isCodeEdit(tool, info.args)) noteEdit(st.check);+ return;+ }+ if (tool !== "bash" && tool !== "shell") return;+ const command = typeof info.args?.command === "string" ? info.args.command : "";+ const exit = typeof output.metadata?.exit === "number" ? output.metadata.exit : null;+ if (on.projectNotes && exit === 0 && devCommand(command)) {+ st.worked.push(command);+ if (st.worked.length > 50) st.worked.shift();+ }+ if (on.selfCheck && isCheckCommand(command, checks())) {+ const text = typeof output.output === "string" ? output.output : String(output.metadata?.output ?? "");+ const result = parseCheckResult(text, exit, command);+ noteCheckRun(st.check, result);+ const [title, ...rest] = result.summary.split(": ");+ toast(title, rest.join(": "), result.ok ? "success" : "warning");+ }+ };++ {+ 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;+ 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 }],+ };+ };+ }++ // 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);++ hooks.event = async ({ event } = {}) => {+ const id = event?.properties?.sessionID;+ if (!id || !sessions.has(id)) return;+ const st = sessions.get(id);+ if (event.type === "session.compacted" || event.type === "session.error") st.compactingSince = 0;+ if (event.type !== "session.idle") return;+ st.compactingSince = 0;+ st.notesAllowed = false;+ const on = flags();+ if (on.selfCheck && st.check.edits > 0 && !st.check.skip && checks().length > 0) {+ toast("Not checked", `Code changed after the last check. Ask the agent to run \`${checks()[0].command}\`.`, "warning");+ }+ if (on.projectNotes) {+ const fresh = learnedCommands(st.worked, root).filter((command) => !st.offered.has(command));+ if (fresh.length) {+ for (const command of fresh) st.offered.add(command);+ toast("Project notes", `This session found ${fresh.map((c) => `\`${c}\``).join(", ")}. Type /init to add ${fresh.length === 1 ? "it" : "them"} to AGENTS.md.`);+ }+ }+ };++ return hooks;+}diff --git a/apps/server/src/agent-assist/agent-assist.d.ts b/apps/server/src/agent-assist/agent-assist.d.tsnew file mode 100644index 00000000..c02dfc17--- /dev/null+++ b/apps/server/src/agent-assist/agent-assist.d.ts@@ -0,0 +1,49 @@+// Types for agent-assist.js (shared with omnirush-cli; see PARITY.sha256).+export type AgentAssistFeature = "selfCheck" | "projectNotes" | "diagnostics" | "compaction";+export type AgentAssistFlags = Record<AgentAssistFeature, boolean>;+export const FEATURES: AgentAssistFeature[];+export const FEATURES_ENV: string;+export const FEATURES_FILE_ENV: string;+export function featureFlags(input?: { env?: Record<string, string | undefined>; settings?: unknown }): AgentAssistFlags;+export function featuresEnvValue(flags: AgentAssistFlags): string;+export function featuresFromEnv(env?: Record<string, string | undefined>): AgentAssistFlags;+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 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;+export type ProjectCheck = { kind: "typecheck" | "lint" | "test"; command: string };+export function packageManager(root: string): "pnpm" | "yarn" | "bun" | "npm";+export function detectChecks(root: string, options?: { platform?: string }): ProjectCheck[];+export function commandSegments(command: string): string[];+export function isCheckCommand(command: string, checks?: ProjectCheck[]): boolean;+export type CheckResult = { ok: boolean; passed: number | null; failed: number | null; summary: string };+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 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;+export function noteEdit(state: CheckState): void;+export function admitNote(state: CheckState, note: string | null, options?: { repeats?: number }): string | null;+export function newCheckState(): CheckState;+export function noteUserPrompt(state: CheckState, text: string): void;+export function selfCheckNote(state: CheckState, checks: ProjectCheck[], options?: { attempts?: number }): string | null;+export function noteCheckRun(state: CheckState, result: CheckResult): void;+export const NOTES_FILE: string;+export function devCommand(command: string): string | null;+export function learnedCommands(commands: string[], root: string): string[];+export function projectScan(root: string, options?: { learned?: string[] }): string;+export function droppedLines(before: string, after: string): string[];+export function notesLinesDropped(tool: string, args: unknown, root: string): { file: string; lines: string[] }[];+export function notesGuardMessage(drops: { file: string; lines: string[] }[]): string;+export type SessionLedger = { preferences: string[]; decisions: string[]; todos: string[]; worked: string[]; failing: string[]; files: string[] };+export function sessionLedger(messages: unknown[]): SessionLedger;+export function ledgerEmpty(ledger: SessionLedger | null | undefined): boolean;+export function compactionContext(ledger: SessionLedger): string;+export function missingFactsNote(ledger: SessionLedger, summary: string): string | null;+export function latestSummary(messages: unknown[]): { index: number; id: string; created: number; text: string } | null;+export const NOTICE_TITLES: string[];diff --git a/apps/server/src/agent-assist/agent-assist.js b/apps/server/src/agent-assist/agent-assist.jsnew file mode 100644index 00000000..ed1a03d0--- /dev/null+++ b/apps/server/src/agent-assist/agent-assist.js@@ -0,0 +1,772 @@+// Agent assist: self-check after edits, project notes (/init, AGENTS.md),+// code diagnostics (language servers) and fuller compaction summaries.+//+// 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+// 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 path from "node:path";++// --- feature switches ---------------------------------------------------------++export const FEATURES = ["selfCheck", "projectNotes", "diagnostics", "compaction"];+const ENV_SWITCH = {+ selfCheck: "OMNIRUSH_SELF_CHECK",+ projectNotes: "OMNIRUSH_PROJECT_NOTES",+ diagnostics: "OMNIRUSH_CODE_DIAGNOSTICS",+ compaction: "OMNIRUSH_SMART_COMPACTION",+};+/** The env the launcher hands the engine: the features that are on, comma separated. */+export const FEATURES_ENV = "OMNIRUSH_AGENT_ASSIST";++function switchValue(value) {+ const text = String(value ?? "").trim().toLowerCase();+ if (["0", "off", "false", "no"].includes(text)) return false;+ if (["1", "on", "true", "yes"].includes(text)) return true;+ return null;+}++/**+ * Which features are on: an env switch wins (OMNIRUSH_SELF_CHECK=0, ...), then+ * the saved setting (`settings.agentAssist.<feature> === false` turns it off),+ * else on.+ */+export function featureFlags({ env = {}, settings = {} } = {}) {+ const saved = settings && typeof settings === "object" && settings.agentAssist && typeof settings.agentAssist === "object" ? settings.agentAssist : {};+ return Object.fromEntries(FEATURES.map((name) => {+ const forced = switchValue(env[ENV_SWITCH[name]]);+ return [name, forced ?? saved[name] !== false];+ }));+}++export function featuresEnvValue(flags) {+ return FEATURES.filter((name) => flags[name]).join(",");+}++/** The file an app rewrites when its switches change (the desktop app): `{ "features": [...] }`. */+export const FEATURES_FILE_ENV = "OMNIRUSH_AGENT_ASSIST_FILE";++/**+ * The features on: the file named in OMNIRUSH_AGENT_ASSIST_FILE when it can be+ * read, else the list in OMNIRUSH_AGENT_ASSIST, else none.+ */+export function featuresFromEnv(env = {}) {+ let raw = typeof env[FEATURES_ENV] === "string" ? env[FEATURES_ENV] : null;+ const file = typeof env[FEATURES_FILE_ENV] === "string" ? env[FEATURES_FILE_ENV].trim() : "";+ if (file) {+ try {+ const saved = JSON.parse(fs.readFileSync(file, "utf8"));+ if (Array.isArray(saved?.features)) raw = saved.features.filter((item) => typeof item === "string").join(",");+ } catch { /* not written yet: the env's list */ }+ }+ if (raw === null) return Object.fromEntries(FEATURES.map((name) => [name, false]));+ const on = new Set(raw.split(",").map((item) => item.trim()));+ return Object.fromEntries(FEATURES.map((name) => [name, on.has(name)]));+}++// --- code diagnostics (language servers) ---------------------------------------++/** The engine's built-in language servers (its ConfigLSPV1 list). */+export const LSP_BUILTIN_IDS = [+ "deno", "typescript", "vue", "eslint", "oxlint", "biome", "gopls", "ruby-lsp", "ty", "pyright",+ "elixir-ls", "zls", "csharp", "razor", "fsharp", "sourcekit-lsp", "rust", "clangd", "svelte", "astro",+ "jdtls", "kotlin-ls", "yaml-ls", "lua-ls", "php intelephense", "prisma", "dart", "ocaml-lsp", "bash",+ "terraform", "texlab", "dockerfile", "gleam", "clojure-lsp", "nixd", "tinymist", "haskell-language-server", "julials",+];+/**+ * The servers left on: TypeScript/JavaScript, Python, Go and Rust (deno only+ * runs where a deno.json is and deno is installed). The rest stay off: several+ * download hundreds of megabytes (Java, Kotlin, C#) or start a second server+ * 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. */+export const LSP_HEAP_MB = 3072;++/** The engine config's `lsp` value: every built-in server but the enabled ones turned off. */+export function lspConfig() {+ return Object.fromEntries(LSP_BUILTIN_IDS.filter((id) => !LSP_ENABLED_IDS.includes(id)).map((id) => [id, { disabled: true }]));+}++/**+ * Engine env for the diagnostics: the Node-based servers inherit the engine's+ * env, so NODE_OPTIONS carries their heap cap. The person's own NODE_OPTIONS is+ * 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 = {}) {+ 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) };+}++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 : "";+}++const DIAG_BLOCK = /(\n*LSP errors detected in [^\n]*:\n)?<diagnostics file="([^"]*)">\n([\s\S]*?)\n<\/diagnostics>/g;+/** An error about the environment, not the code: a package that is not installed here. */+function environmentNoise(line) {+ const ts = /Cannot find module '([^']+)' or its corresponding type declarations/.exec(line);+ if (ts) return !/^[./]/.test(ts[1]);+ const py = /Import "([^"]+)" could not be resolved/.exec(line);+ if (py) return !py[1].startsWith(".");+ return false;+}++/**+ * A file tool's output with the language servers' "not installed" errors taken+ * out (a package missing on this machine is not a mistake in the edit; in a+ * sandbox the packages are often installed only there). A block left empty is+ * removed with its heading.+ */+export function filterDiagnosticsOutput(text) {+ if (typeof text !== "string" || !text.includes("<diagnostics")) return { text, removed: 0, kept: 0 };+ let removed = 0;+ let kept = 0;+ const out = text.replace(DIAG_BLOCK, (whole, heading, file, body) => {+ const lines = body.split("\n");+ const left = lines.filter((line) => {+ if (/^\.\.\. and \d+ more$/.test(line)) return true;+ if (environmentNoise(line)) { removed += 1; return false; }+ return true;+ });+ const real = left.filter((line) => !/^\.\.\. and \d+ more$/.test(line));+ kept += real.length;+ if (real.length === 0) return "";+ return `${heading ?? ""}<diagnostics file="${file}">\n${left.join("\n")}\n</diagnostics>`;+ });+ return { text: out, removed, kept };+}++/** At most `files` files of at most `per` entries each in a tool's diagnostics metadata (upload size). */+export function capDiagnosticsMetadata(map, { files = 10, per = 20 } = {}) {+ if (!map || typeof map !== "object" || Array.isArray(map)) return map;+ const entries = Object.entries(map).filter(([, list]) => Array.isArray(list) && list.length > 0);+ return Object.fromEntries(entries.slice(0, files).map(([file, list]) => [file, list.slice(0, per)]));+}++// --- project checks -------------------------------------------------------------++function readText(file, limit = 512 * 1024) {+ try {+ const stat = fs.statSync(file);+ if (!stat.isFile() || stat.size > limit) return null;+ return fs.readFileSync(file, "utf8");+ } catch {+ return null;+ }+}++function exists(file) {+ try { return fs.existsSync(file); } catch { return false; }+}++function readJson(file) {+ const text = readText(file);+ if (text === null) return null;+ try { return JSON.parse(text); } catch { return null; }+}++export function packageManager(root) {+ if (exists(path.join(root, "pnpm-lock.yaml"))) return "pnpm";+ if (exists(path.join(root, "yarn.lock"))) return "yarn";+ if (exists(path.join(root, "bun.lock")) || exists(path.join(root, "bun.lockb"))) return "bun";+ return "npm";+}++function runScript(pm, name) {+ if (name === "test") return pm === "bun" ? "bun run test" : `${pm} test`;+ return pm === "npm" ? `npm run ${name}` : `${pm} run ${name}`;+}++const NO_TEST = /no test specified/i;+const TYPECHECK_SCRIPTS = ["typecheck", "type-check", "check-types", "types", "tsc"];++function makeTargets(root) {+ const text = readText(path.join(root, "Makefile")) ?? readText(path.join(root, "makefile"));+ if (!text) return [];+ const targets = [];+ for (const match of text.matchAll(/^([A-Za-z0-9][\w.-]*)\s*:(?!=)/gm)) {+ if (!targets.includes(match[1]) && !match[1].startsWith(".")) targets.push(match[1]);+ }+ return targets;+}++function hasPythonTests(root) {+ if (["pytest.ini", "conftest.py", "tox.ini"].some((name) => exists(path.join(root, name)))) return true;+ const pyproject = readText(path.join(root, "pyproject.toml")) ?? "";+ if (/\[tool\.pytest/.test(pyproject)) return true;+ for (const dir of ["tests", "test"]) {+ try {+ if (fs.readdirSync(path.join(root, dir)).some((name) => /^test_.*\.py$|_test\.py$/.test(name))) return true;+ } catch { /* none */ }+ }+ try {+ return fs.readdirSync(root).some((name) => /^test_.*\.py$/.test(name));+ } catch {+ return false;+ }+}++/**+ * The project's checks, cheapest first: [{ kind, command }] with kind+ * typecheck | lint | test. Read from package.json scripts, Python test setup,+ * go.mod, Cargo.toml, else a Makefile's test/check/lint targets. At most three.+ */+export function detectChecks(root, { platform = process.platform } = {}) {+ const checks = [];+ const add = (kind, command) => {+ if (checks.length < 3 && !checks.some((item) => item.command === command)) checks.push({ kind, command });+ };+ const pkg = readJson(path.join(root, "package.json"));+ if (pkg && typeof pkg === "object") {+ const scripts = pkg.scripts && typeof pkg.scripts === "object" ? pkg.scripts : {};+ const pm = packageManager(root);+ const typecheck = TYPECHECK_SCRIPTS.find((name) => typeof scripts[name] === "string");+ if (typecheck) add("typecheck", runScript(pm, typecheck));+ if (typeof scripts.lint === "string") add("lint", runScript(pm, "lint"));+ if (typeof scripts.test === "string" && !NO_TEST.test(scripts.test)) add("test", runScript(pm, "test"));+ }+ const pyproject = readText(path.join(root, "pyproject.toml")) ?? "";+ // The project's own runner when it has one; else the interpreter by its usual name here.+ const pyRun = exists(path.join(root, "uv.lock")) ? "uv run " : exists(path.join(root, "poetry.lock")) ? "poetry run " : "";+ const python = pyRun ? `${pyRun}python` : platform === "win32" ? "python" : "python3";+ if (/\[tool\.ruff/.test(pyproject)) add("lint", `${pyRun}ruff check .`);+ if (/\[tool\.mypy/.test(pyproject)) add("typecheck", `${pyRun}mypy .`);+ if (hasPythonTests(root)) add("test", `${python} -m pytest -q`);+ if (exists(path.join(root, "go.mod"))) {+ add("lint", "go vet ./...");+ add("test", "go test ./...");+ }+ if (exists(path.join(root, "Cargo.toml"))) add("test", "cargo test");+ if (checks.length === 0) {+ const targets = makeTargets(root);+ for (const target of ["check", "lint", "test"]) if (targets.includes(target)) add(target === "test" ? "test" : "lint", `make ${target}`);+ }+ return checks;+}++const TEST_RUNNERS = /^(?:(?:npx|pnpx|bunx|pnpm exec|yarn exec)\s+)?(?:vitest|jest|mocha|ava|tap|pytest|tsc(?:\s|$)|eslint|ruff|mypy|pyright|biome\s+check|oxlint)\b|^(?:python3?|py)\s+-m\s+(?:pytest|unittest|mypy|ruff)\b|^(?:go\s+(?:test|vet)|cargo\s+(?:test|check|clippy)|make\s+(?:test|check|lint)|node\s+--test|bun\s+test|deno\s+(?:test|check|lint))\b|^(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|typecheck|type-check|check-types|check)(?::[\w:-]+)?\b/;++/** The command's parts that run something (`cd x && npm test | tail` -> ["npm test"]). */+export function commandSegments(command) {+ return String(command || "")+ .split(/&&|\|\||;|\n/)+ .map((part) => part.split("|")[0].trim())+ .map((part) => part.replace(/^(?:[A-Z_][A-Z0-9_]*=\S*\s+)+/, "").replace(/^(?:timeout\s+\d+[smh]?\s+)/, ""))+ .filter((part) => part && !/^cd\s/.test(part));+}++/** Whether a shell command runs one of the project's checks (or a well-known test runner, linter, type checker). */+export function isCheckCommand(command, checks = []) {+ return commandSegments(command).some((part) =>+ checks.some((check) => part === check.command || part.startsWith(`${check.command} `)) || TEST_RUNNERS.test(part));+}++function count(text, pattern) {+ const match = pattern.exec(text);+ return match ? Number(match[1]) : null;+}++/**+ * The counts in a check's output (vitest, jest, node --test, pytest, go test,+ * cargo test, mocha, tsc, eslint) and a one-line summary:+ * "Checked: 42 tests passed" / "Check failed: 2 of 42 tests failed".+ */+export function parseCheckResult(output, exitCode, command = "") {+ const text = String(output || "").replace(/\u001b\[[0-9;]*m/g, "");+ let passed = null;+ let failed = null;+ const vitest = /Tests\s+(?:(\d+) failed\s*\|\s*)?(\d+) passed/.exec(text);+ if (vitest) { failed = Number(vitest[1] ?? 0); passed = Number(vitest[2]); }+ const jest = /Tests:\s+(?:(\d+) failed,\s*)?(?:\d+ skipped,\s*)?(\d+) passed/.exec(text);+ if (passed === null && jest) { failed = Number(jest[1] ?? 0); passed = Number(jest[2]); }+ if (passed === null && /^(?:# |ℹ )pass \d+/m.test(text)) {+ passed = count(text, /^(?:# |ℹ )pass (\d+)/m);+ failed = count(text, /^(?:# |ℹ )fail (\d+)/m) ?? 0;+ }+ if (passed === null) {+ const pytest = /=+ (?:(\d+) failed, )?(\d+) passed|=+ (\d+) failed/.exec(text);+ if (pytest) { failed = Number(pytest[1] ?? pytest[3] ?? 0); passed = Number(pytest[2] ?? 0); }+ }+ if (passed === null) {+ const cargo = [...text.matchAll(/test result: \w+\. (\d+) passed; (\d+) failed/g)];+ if (cargo.length) { passed = cargo.reduce((sum, m) => sum + Number(m[1]), 0); failed = cargo.reduce((sum, m) => sum + Number(m[2]), 0); }+ }+ if (passed === null) {+ const mocha = /(\d+) passing/.exec(text);+ if (mocha) { passed = Number(mocha[1]); failed = count(text, /(\d+) failing/) ?? 0; }+ }+ if (passed === null && /^(?:ok|FAIL|---)\s/m.test(text) && /\bgo\s+test\b/.test(command)) {+ passed = (text.match(/^ok\s/gm) || []).length;+ failed = (text.match(/^FAIL\s/gm) || []).length;+ }+ 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);+ const unit = /\bgo\s+test\b/.test(command) ? "packages" : "tests";+ let summary;+ if (passed !== null) {+ const total = passed + (failed ?? 0);+ summary = ok && !failed ? `Checked: ${passed} ${passed === 1 ? unit.replace(/s$/, "") : unit} passed` : `Check failed: ${failed || "some"} of ${total} ${unit} failed`;+ } else if (tscErrors !== null && !ok) {+ summary = `Check failed: ${tscErrors} type error${tscErrors === 1 ? "" : "s"}`;+ } else if (eslintProblems !== null && !ok) {+ summary = `Check failed: ${eslintProblems} lint problem${eslintProblems === 1 ? "" : "s"}`;+ } else {+ const label = commandSegments(command).find((part) => TEST_RUNNERS.test(part)) || commandSegments(command)[0] || "check";+ summary = ok ? `Checked: ${label} passed` : `Check failed: ${label} exited with ${exitCode ?? "an error"}`;+ }+ return { ok, passed, failed, summary };+}++const EDIT_TOOLS = new Set(["edit", "write", "apply_patch", "multiedit", "patch"]);+const NOT_CODE = /\.(?:md|mdx|txt|rst|adoc|log|csv|png|jpe?g|gif|svg|ico|lock)$/i;++function editedPaths(tool, args) {+ if (!args || typeof args !== "object") return [];+ if (typeof args.filePath === "string") return [args.filePath];+ if (typeof args.path === "string") return [args.path];+ if (typeof args.patchText === "string") {+ return [...args.patchText.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)].map((m) => m[1].trim());+ }+ return [];+}++/** Whether a file tool call changed code (not only notes, docs or images). */+export function isCodeEdit(tool, args) {+ if (!EDIT_TOOLS.has(String(tool || "").toLowerCase())) return false;+ const files = editedPaths(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"). */+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 || ""));+}++export const SELF_CHECK_ATTEMPTS = 3;++/** Model calls in a row a note is shown without an edit or a check run in between (a stuck turn): after this many it is dropped. */+export const SELF_CHECK_NOTE_REPEATS = 8;++export function newCheckState() {+ return { edits: 0, failures: 0, ran: 0, skip: false, last: null, shown: 0 };+}++/** A code edit: a check is due again. */+export function noteEdit(state) {+ state.edits += 1;+ state.shown = 0;+}++/**+ * The note to add to this model call: `note`, unless it has been shown+ * SELF_CHECK_NOTE_REPEATS calls in a row with no edit or check run since (the+ * model is not making progress; the note would only keep the turn going).+ */+export function admitNote(state, note, { repeats = SELF_CHECK_NOTE_REPEATS } = {}) {+ if (!note) return null;+ state.shown = (state.shown ?? 0) + 1;+ return state.shown <= repeats ? note : null;+}++/** A new prompt from the person: a new turn's budget, and its skip request. */+export function noteUserPrompt(state, text) {+ state.failures = 0;+ state.shown = 0;+ state.skip = skipRequested(text);+}++/**+ * The system note for the next model call while code changed since the last+ * check: run the checks; after a failure, fix and re-run; after the attempts+ * are used up, stop and report. Null when nothing is due.+ */+export function selfCheckNote(state, checks, { attempts = SELF_CHECK_ATTEMPTS } = {}) {+ if (!state || state.skip || checks.length === 0) return null;+ if (state.failures >= attempts) {+ if (state.edits === 0 && state.last && !state.last.ok) {+ return `Self-check: the project's checks failed ${state.failures} times in this turn (last: ${state.last.summary}). Stop retrying. In your reply, say what still fails and why.`;+ }+ return null;+ }+ if (state.edits === 0) {+ if (state.last && !state.last.ok) {+ return `Self-check: the last check failed (attempt ${state.failures} of ${attempts}): ${state.last.summary}. Fix the cause if your change caused it, then run the checks again. If the failure is unrelated to your change, say so in your reply instead.`;+ }+ return null;+ }+ const list = checks.map((check) => `- \`${check.command}\``).join("\n");+ return [+ "Self-check: you changed code in this project since the last check. Before you say the work is done, run the project's checks with the shell tool and fix failures your change caused:",+ list,+ "Give each command a timeout of at most 5 minutes. If a check cannot run here (a missing tool or service) or fails for reasons unrelated to your change, say so in your reply instead of retrying. End your reply with the result in one line, for example \"Checked: 42 tests passed\".",+ ].join("\n");+}++/** A finished shell call that ran a check: the state, and the summary to show. */+export function noteCheckRun(state, result) {+ state.ran += 1;+ state.edits = 0;+ state.shown = 0;+ state.last = result;+ state.failures = result.ok ? 0 : state.failures + 1;+}++// --- project notes (AGENTS.md) -----------------------------------------------------++export const NOTES_FILE = "AGENTS.md";+const INSTRUCTION_FILES = ["AGENTS.md", "CLAUDE.md", ".cursorrules", ".cursor/rules", ".github/copilot-instructions.md", "CONTRIBUTING.md"];++const DEV_COMMAND = /^(?:(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?!install\b|i\b|ci\b|add\b|remove\b|uninstall\b|update\b|init\b|create\b|exec\b|dlx\b|x\b|outdated\b|audit\b|view\b|info\b|ls\b|why\b|link\b|publish\b|version\b|login\b|config\b|cache\b|help\b|--)[\w:.-]+|(?:npx|pnpx|bunx)\s+(?:vitest|jest|tsc|eslint|prettier|playwright|prisma|drizzle-kit|next|vite)\b|(?:python3?|py)\s+-m\s+(?:pytest|unittest|mypy|ruff|black|flask|uvicorn|alembic)\b|(?:pytest|ruff|mypy|black|uvicorn|alembic)\b|go\s+(?:test|build|vet|run|generate)\b|cargo\s+(?:test|build|check|clippy|run|fmt)\b|make\s+[\w.-]+|tsc\b|deno\s+(?:task|test|check|lint|run)\b|docker\s+compose\s+up\b|(?:gradle|\.\/gradlew|mvn)\s+\w+|dotnet\s+(?:test|build|run)\b)/;++function normalizeCommand(text) {+ return String(text || "").replace(/\s+/g, " ").trim();+}++/** A shell call's command shortened to what a project note would show (`cd x && npm test -- --run` -> "npm test -- --run"). */+export function devCommand(command) {+ for (const part of commandSegments(command)) {+ if (DEV_COMMAND.test(part)) return normalizeCommand(part).slice(0, 120);+ }+ return null;+}++function notesText(root) {+ return [readText(path.join(root, NOTES_FILE)) ?? "", readText(path.join(root, "CLAUDE.md")) ?? ""].join("\n");+}++/** Commands that worked in a session and that the project's notes do not mention yet. */+export function learnedCommands(commandsThatWorked, root) {+ const notes = normalizeCommand(notesText(root)).toLowerCase();+ const seen = new Set();+ const out = [];+ for (const raw of commandsThatWorked) {+ const command = devCommand(raw);+ if (!command || seen.has(command)) continue;+ seen.add(command);+ const head = command.split(" ").slice(0, 3).join(" ").toLowerCase();+ if (notes.includes(command.toLowerCase()) || notes.includes(head)) continue;+ out.push(command);+ }+ return out.slice(0, 5);+}++function workflowRuns(root) {+ const dir = path.join(root, ".github", "workflows");+ let names = [];+ try { names = fs.readdirSync(dir).filter((name) => /\.ya?ml$/.test(name)).slice(0, 6); } catch { return []; }+ const runs = [];+ for (const name of names) {+ const text = readText(path.join(dir, name)) ?? "";+ for (const match of text.matchAll(/^\s*-?\s*run:\s*(?!\|)(.+)$/gm)) {+ const command = normalizeCommand(match[1]).replace(/^["']|["']$/g, "");+ if (command && !runs.some((item) => item.command === command)) runs.push({ file: name, command });+ if (runs.length >= 12) return runs;+ }+ }+ return runs;+}++/**+ * Facts read from the repository for /init: its manifests' commands, checks,+ * CI steps, existing instruction files, commands that worked in this session.+ * Markdown, model-facing, for the agent to verify and write up.+ */+export function projectScan(root, { learned = [] } = {}) {+ const lines = ["Repository facts gathered automatically for this task (verify them; they are a starting point, not the content):"];+ const pkg = readJson(path.join(root, "package.json"));+ if (pkg && typeof pkg === "object") {+ const pm = packageManager(root);+ lines.push(`- Node project (package manager: ${pm}${pkg.workspaces || exists(path.join(root, "pnpm-workspace.yaml")) ? ", workspaces" : ""}).`);+ const scripts = pkg.scripts && typeof pkg.scripts === "object" ? Object.entries(pkg.scripts).filter(([, value]) => typeof value === "string") : [];+ for (const [name, value] of scripts.slice(0, 15)) lines.push(` - \`${runScript(pm, name)}\` runs \`${normalizeCommand(value).slice(0, 100)}\``);+ }+ const pyproject = readText(path.join(root, "pyproject.toml"));+ if (pyproject !== null || exists(path.join(root, "requirements.txt")) || exists(path.join(root, "setup.py"))) {+ const tools = [...new Set([...(pyproject ?? "").matchAll(/^\[tool\.([\w-]+)/gm)].map((m) => m[1]))];+ const manager = exists(path.join(root, "uv.lock")) ? "uv" : exists(path.join(root, "poetry.lock")) ? "poetry" : null;+ lines.push(`- Python project${manager ? ` (${manager})` : ""}${tools.length ? `; tool config: ${tools.slice(0, 8).join(", ")}` : ""}.`);+ }+ const gomod = readText(path.join(root, "go.mod"));+ if (gomod !== null) lines.push(`- Go module ${(/^module\s+(\S+)/m.exec(gomod) || [])[1] ?? ""}`.trimEnd() + ".");+ const cargo = readText(path.join(root, "Cargo.toml"));+ if (cargo !== null) lines.push(`- Rust ${/\[workspace\]/.test(cargo) ? "workspace" : "crate"}.`);+ const targets = makeTargets(root);+ if (targets.length) lines.push(`- Makefile targets: ${targets.slice(0, 15).map((t) => `\`make ${t}\``).join(", ")}.`);+ const checks = detectChecks(root);+ if (checks.length) lines.push(`- Checks to run after changes: ${checks.map((c) => `\`${c.command}\` (${c.kind})`).join(", ")}.`);+ const runs = workflowRuns(root);+ if (runs.length) {+ lines.push("- CI steps:");+ for (const run of runs) lines.push(` - \`${run.command.slice(0, 120)}\` (${run.file})`);+ }+ const instructions = INSTRUCTION_FILES.filter((name) => exists(path.join(root, name)));+ if (instructions.length) lines.push(`- Existing instruction files: ${instructions.join(", ")}.`);+ if (learned.length) {+ lines.push("- Commands that worked in this session:");+ for (const command of learned) lines.push(` - \`${command}\``);+ }+ const notes = readText(path.join(root, NOTES_FILE));+ lines.push("");+ if (notes !== null && notes.trim()) {+ lines.push(`${NOTES_FILE} already exists (${notes.split("\n").length} lines). Keep every line already in it. Add new facts as new lines or sections. To change or remove an existing line, first show the person the exact diff and ask; change it only after they agree.`);+ } else {+ lines.push(`${NOTES_FILE} does not exist yet: create it.`);+ }+ return lines.join("\n");+}++function nonBlankLines(text) {+ return String(text || "").split("\n").map((line) => line.trim()).filter(Boolean);+}++/** Lines of `before` (non-blank) that `after` no longer has: the person's lines a change would drop. */+export function droppedLines(before, after) {+ const left = new Map();+ for (const line of nonBlankLines(after)) left.set(line, (left.get(line) ?? 0) + 1);+ const dropped = [];+ for (const line of nonBlankLines(before)) {+ const n = left.get(line) ?? 0;+ if (n > 0) left.set(line, n - 1);+ else dropped.push(line);+ }+ return dropped;+}++function isNotesFile(file, root) {+ 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));+}++/**+ * What a file tool call would drop from an existing AGENTS.md: [{ file, lines }]+ * (empty when it only adds). Reads the file as it is now.+ */+export function notesLinesDropped(tool, args, root) {+ const name = String(tool || "").toLowerCase();+ if (!args || typeof args !== "object") return [];+ const out = [];+ const current = (file) => readText(path.resolve(root, file));+ if ((name === "write" || name === "edit" || name === "multiedit") && isNotesFile(args.filePath ?? args.path, root)) {+ const file = args.filePath ?? args.path;+ const before = current(file);+ if (before === null || !before.trim()) return [];+ let after = before;+ if (name === "write") after = typeof args.content === "string" ? args.content : "";+ else {+ const edits = Array.isArray(args.edits) ? args.edits : [args];+ for (const edit of edits) {+ const oldString = typeof edit.oldString === "string" ? edit.oldString : "";+ const newString = typeof edit.newString === "string" ? edit.newString : "";+ if (!oldString) { after = newString; continue; }+ after = edit.replaceAll ? after.split(oldString).join(newString) : after.replace(oldString, () => newString);+ }+ }+ const lines = droppedLines(before, after);+ if (lines.length) out.push({ file, lines });+ return out;+ }+ if ((name === "apply_patch" || name === "patch") && typeof args.patchText === "string") {+ const sections = args.patchText.split(/^(?=\*\*\* (?:Add|Update|Delete) File: )/m);+ for (const section of sections) {+ const head = /^\*\*\* (Add|Update|Delete) File: (.+)$/m.exec(section);+ if (!head || !isNotesFile(head[2].trim(), root)) continue;+ const file = head[2].trim();+ const before = current(file);+ if (before === null || !before.trim()) continue;+ let lines;+ if (head[1] === "Delete") lines = nonBlankLines(before);+ else if (head[1] === "Add") lines = droppedLines(before, section.split("\n").slice(1).filter((l) => l.startsWith("+")).map((l) => l.slice(1)).join("\n"));+ else {+ const removed = section.split("\n").filter((l) => l.startsWith("-") && !l.startsWith("---")).map((l) => l.slice(1));+ const added = section.split("\n").filter((l) => l.startsWith("+") && !l.startsWith("+++")).map((l) => l.slice(1));+ lines = droppedLines(removed.join("\n"), added.join("\n"));+ }+ if (lines.length) out.push({ file, lines });+ }+ }+ return out;+}++/** The model-facing refusal for a change that would drop the person's lines from AGENTS.md. */+export function notesGuardMessage(drops) {+ const total = drops.reduce((sum, d) => sum + d.lines.length, 0);+ const shown = drops.flatMap((d) => d.lines.slice(0, 12).map((line) => `- ${line}`));+ return [+ `Not applied: this change would remove or rewrite ${total} existing line${total === 1 ? "" : "s"} of ${drops.map((d) => d.file).join(", ")}, which the person may have written:`,+ ...shown,+ ...(total > shown.length ? [`... and ${total - shown.length} more`] : []),+ "Show the person this diff and ask whether to apply it; apply it only after they agree. Adding new lines needs no confirmation.",+ ].join("\n");+}++// --- 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 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) {+ return String(text || "")+ .split(/(?<=[.!?])\s+|\n+/)+ .map((s) => s.replace(/\s+/g, " ").trim())+ .filter((s) => s.length >= 8 && s.length <= 300);+}++function pushUnique(list, value, limit) {+ const i = list.indexOf(value);+ if (i >= 0) list.splice(i, 1);+ list.push(value);+ if (list.length > limit) list.shift();+}++function partsOf(message) {+ return Array.isArray(message?.parts) ? message.parts : [];+}++/**+ * Facts from a whole session (engine messages: { info, parts }) that a+ * compaction summary must carry: the person's preferences and directives,+ * decisions, open to-dos, commands that worked (and ones still failing), the+ * files changed and how.+ */+export function sessionLedger(messages) {+ const ledger = { preferences: [], decisions: [], todos: [], worked: [], failing: [], files: [] };+ const fileState = new Map();+ for (const message of Array.isArray(messages) ? messages : []) {+ const role = message?.info?.role;+ if (role === "assistant" && message.info.summary) continue;+ 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);+ if (DECISION.test(sentence)) pushUnique(ledger.decisions, sentence, 10);+ }+ }+ if (part?.type !== "tool" || !part.state) continue;+ const tool = String(part.tool || "").toLowerCase();+ const input = part.state.input && typeof part.state.input === "object" ? part.state.input : {};+ if (tool === "todowrite" && Array.isArray(input.todos)) {+ ledger.todos = input.todos+ .filter((todo) => todo && typeof todo.content === "string" && !["completed", "cancelled"].includes(todo.status))+ .map((todo) => `${todo.content}${todo.status === "in_progress" ? " (in progress)" : ""}`)+ .slice(0, 15);+ }+ if (part.state.status !== "completed") continue;+ if (tool === "bash" || tool === "shell") {+ const command = devCommand(input.command);+ const exit = part.state.metadata?.exit;+ if (!command) continue;+ if (exit === 0) {+ pushUnique(ledger.worked, command, 15);+ ledger.failing = ledger.failing.filter((item) => !item.startsWith(`${command} `) && item !== command);+ } else if (typeof exit === "number") {+ const note = `${command} (exit ${exit})`;+ ledger.failing = ledger.failing.filter((item) => !item.startsWith(`${command} (`));+ pushUnique(ledger.failing, note, 8);+ }+ }+ if (EDIT_TOOLS.has(tool)) {+ const meta = part.state.metadata ?? {};+ for (const file of editedPaths(tool, input)) {+ const prior = fileState.get(file);+ const created = tool === "write" && meta.exists === false;+ const deleted = tool === "apply_patch" && new RegExp(`^\\*\\*\\* Delete File: ${file.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`, "m").test(String(input.patchText || ""));+ const state = deleted ? "deleted" : created && !prior ? "created" : prior === "created" ? "created" : "edited";+ fileState.delete(file);+ fileState.set(file, state);+ }+ }+ }+ }+ ledger.files = [...fileState.entries()].slice(-30).map(([file, state]) => `${file} (${state})`);+ return ledger;+}++const LEDGER_SECTIONS = [+ ["preferences", "User Preferences"],+ ["decisions", "Decisions"],+ ["todos", "Open To-dos"],+ ["worked", "Commands That Worked"],+ ["failing", "Commands Still Failing"],+ ["files", "File State"],+];++export function ledgerEmpty(ledger) {+ return !ledger || LEDGER_SECTIONS.every(([key]) => !Array.isArray(ledger[key]) || ledger[key].length === 0);+}++/**+ * Added to the engine's compaction prompt (after its template): four more+ * sections and the ledger of facts from the whole session, including parts+ * an earlier compaction already folded away.+ */+export function compactionContext(ledger) {+ const lines = [+ "After the template's last section, add these sections in this order, keeping each even when empty (\"(none)\"):",+ "## User Preferences — the person's instructions and preferences, quoted closely",+ "## Decisions — what was decided and why",+ "## Open To-dos — unfinished items",+ "## Commands That Worked — exact commands (build, test, run) known to work here",+ "Keep exact file paths and commands.",+ ];+ if (!ledgerEmpty(ledger)) {+ lines.push("", "<session-facts>", "Facts from the whole session, including parts summarized before. Carry each one into the matching section unless it is finished and no longer needed:");+ for (const [key, title] of LEDGER_SECTIONS) {+ if (!ledger[key]?.length) continue;+ lines.push(`${title}:`);+ for (const item of ledger[key]) lines.push(`- ${item}`);+ }+ lines.push("</session-facts>");+ }+ return lines.join("\n");+}++/**+ * The ledger's facts a summary left out, as a note to keep beside it in the+ * model's context (null when the summary has them all). A fact counts as kept+ * when its distinctive text (its first 40 characters, lowercased) is in the+ * summary.+ */+export function missingFactsNote(ledger, summary) {+ if (ledgerEmpty(ledger)) return null;+ const haystack = String(summary || "").toLowerCase().replace(/\s+/g, " ");+ const lines = [];+ for (const [key, title] of LEDGER_SECTIONS) {+ const missing = (ledger[key] ?? []).filter((item) => {+ const probe = item.replace(/\s+\((?:created|edited|deleted|in progress|exit \d+)\)$/, "").toLowerCase().replace(/\s+/g, " ").slice(0, 40);+ return !haystack.includes(probe);+ });+ if (!missing.length) continue;+ lines.push(`${title}:`);+ for (const item of missing) lines.push(`- ${item}`);+ }+ if (!lines.length) return null;+ return ["<session-facts>", "Facts from earlier in this session that the summary above does not mention:", ...lines, "</session-facts>"].join("\n");+}++/** The message ids and text of the newest finished compaction summary in a message list (engine shape). */+export function latestSummary(messages) {+ for (let i = (messages?.length ?? 0) - 1; i >= 0; i -= 1) {+ const info = messages[i]?.info;+ if (info?.role === "assistant" && info.summary && !info.error) {+ const text = partsOf(messages[i]).filter((p) => p?.type === "text" && typeof p.text === "string").map((p) => p.text).join("\n");+ return { index: i, id: info.id, created: info.time?.created ?? 0, text };+ }+ }+ return null;+}++// --- notices ----------------------------------------------------------------------++/** Toast titles the plugin uses; the desktop app shows engine toasts with these titles only. */+export const NOTICE_TITLES = ["Checked", "Check failed", "Not checked", "Project notes"];diff --git a/apps/server/src/embedded.ts b/apps/server/src/embedded.tsindex 728c9a4a..0758423e 100644--- a/apps/server/src/embedded.ts+++ b/apps/server/src/embedded.ts@@ -5,6 +5,7 @@* 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 { randomUUID } from "node:crypto";import { stopTaskRecovery } from "./task-recovery.js";import { managedDesktopPolicy } from "./managed-desktop-policy.js";@@ -276,6 +277,8 @@ export async function startEmbeddedServer(options: EmbeddedServerOptions): PromiOPENCODE_CONFIG: runtimeConfigPath,...opencodeModelsEnv,...pluginsNoDepsEnv(omnirushOwnPluginPaths()),+ // Agent assist: the plugin's switch file and notes folder, the language servers' heap cap.+ ...agentAssistEngineEnv(config),};engineSpawnTemplate = {bin: opencodeBin,diff --git a/apps/server/src/omnirush-extensions-plugin-path.ts b/apps/server/src/omnirush-extensions-plugin-path.tsindex 12d6c0a7..e1c8d7d9 100644--- a/apps/server/src/omnirush-extensions-plugin-path.ts+++ b/apps/server/src/omnirush-extensions-plugin-path.ts@@ -45,3 +45,4 @@ export const omnirushSwarmPluginPath = () => omnirushPluginPath("omnirush-swarm"export const omnirushMcpPolicyPluginPath = () => omnirushPluginPath("omnirush-mcp-policy");export const omnirushBudgetWrapPluginPath = () => omnirushPluginPath("omnirush-budget-wrap");export const omnirushBuildathonPluginPath = () => omnirushPluginPath("omnirush-buildathon");+export const omnirushAgentAssistPluginPath = () => omnirushPluginPath("omnirush-agent-assist");diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.tsindex 55f316c2..4321e2a1 100644--- a/apps/server/src/omnirush-runtime-config.ts+++ b/apps/server/src/omnirush-runtime-config.ts@@ -33,7 +33,9 @@ import {omnirushChromeDevtoolsPluginPath,omnirushPdfAttachmentsPluginPath,omnirushPluginPath,+ omnirushAgentAssistPluginPath,} from "./omnirush-extensions-plugin-path.js";+import { agentAssistFlags, agentAssistLspConfig, writeAgentAssistFile } from "./agent-assist-config.js";import type { ServerConfig } from "./types.js";import { runtimeStorageDir } from "./runtime-db.js";import {@@ -176,6 +178,8 @@ function omnirushLeadingPluginPaths(): string[] {omnirushSwarmPluginPath(),// Buildathon projects only (the app lists them): the event's reproducibility rules.omnirushBuildathonPluginPath(),+ // Self-check, project notes, diagnostics, compaction (agent-assist-config.ts); inert while all are off.+ omnirushAgentAssistPluginPath(),];}@@ -228,7 +232,9 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(// OMNIRUSH_APPROVALS in the server environment wins over the persisted setting.const permissions = legacyExecutionPermissions(runtimeConfig.managedPolicy?.execution, resolveApprovalMode(runtimeConfig, env).mode);const mcpPermission = { "mcp.*": "deny" };- const { managedPolicy: _managedPolicy, approvals: _approvals, bestPractices: _bestPractices, ...engineConfig } = runtimeConfig;+ const { managedPolicy: _managedPolicy, approvals: _approvals, bestPractices: _bestPractices, agentAssist: _agentAssist, ...engineConfig } = runtimeConfig;+ // Code diagnostics: the main languages' servers on, the rest off; the engine default (none) while off.+ const lsp = agentAssistFlags(runtimeConfig, env).diagnostics ? agentAssistLspConfig() : undefined;const enabled = bestPracticesEnabled(runtimeConfig);const skillPaths = [...(skillsDir ? [skillsDir] : []),@@ -312,6 +318,7 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(omnirushMcpPolicyPluginPath(),],...(disabledProviders.length ? { disabled_providers: disabledProviders } : {}),+ ...(lsp ? { lsp } : {}),// MCP is a permanently disabled capability. The policy plugin also// strips project/global MCP entries that the engine discovers itself.mcp: {},@@ -372,6 +379,8 @@ export async function writeOmniRushRuntimeConfigFile(if (bestPracticesEnabled(await readGlobalRuntimeOpencodeConfig(config))) {await writeBestPracticesSkills(config);}+ // The agent assist plugin's switches: rewritten before the config, read by the plugin at its next hook.+ await writeAgentAssistFile(config, agentAssistFlags(await readGlobalRuntimeOpencodeConfig(config))).catch(() => undefined);const content = await buildOmniRushRuntimeConfig(config);const current = await readFile(path, "utf8").catch(() => undefined);if (current === content) return { path, changed: false };diff --git a/apps/server/src/opencode-plugins/omnirush-agent-assist.ts b/apps/server/src/opencode-plugins/omnirush-agent-assist.tsnew file mode 100644index 00000000..0ec77205--- /dev/null+++ b/apps/server/src/opencode-plugins/omnirush-agent-assist.ts@@ -0,0 +1,12 @@+/**+ * Agent assist: self-check after edits, project notes (/init, AGENTS.md), code+ * diagnostics and fuller compaction summaries. The hooks are the CLI's too+ * (../agent-assist/, PARITY). The server names the features that are on in the+ * file OMNIRUSH_AGENT_ASSIST_FILE points at (agent-assist-config.ts), so a+ * change in Settings applies without restarting the engine.+ */+import { agentAssistHooks } from "../agent-assist/agent-assist-hooks.js";++export const OmniRushAgentAssist = async (input: { client?: unknown; directory?: string; worktree?: string }) => agentAssistHooks(input);++export default OmniRushAgentAssist;diff --git a/apps/server/src/runtime-opencode-config-store.ts b/apps/server/src/runtime-opencode-config-store.tsindex 7ee42b2c..3bc8c07b 100644--- a/apps/server/src/runtime-opencode-config-store.ts+++ b/apps/server/src/runtime-opencode-config-store.ts@@ -1,5 +1,6 @@import { desktopConfigSchema, type DesktopConfig } from "@omnirush/types/den/desktop-policies-runtime";import { existsSync } from "node:fs";+import { normalizeAgentAssistSetting, type AgentAssistSetting } from "./agent-assist-config.js";import { parseApprovalMode, type ApprovalMode } from "./approval-mode.js";import { ApiError } from "./errors.js";import {@@ -19,6 +20,8 @@ export type RuntimeOpencodeConfig = {approvals?: { mode: ApprovalMode };/** Bundled development guidance; local engine-global setting, enabled when absent. */bestPractices?: boolean;+ /** Agent assist switches (agent-assist-config.ts); local engine-global setting, every feature on when absent. */+ agentAssist?: AgentAssistSetting;default_agent?: string;plugin?: string[];disabled_providers?: string[];@@ -52,6 +55,7 @@ function normalizeRuntimeOpencodeConfig(value: unknown): RuntimeOpencodeConfig {...(value.managedPolicy !== undefined ? { managedPolicy: desktopConfigSchema.parse(value.managedPolicy) } : {}),...(approvalMode ? { approvals: { mode: approvalMode } } : {}),...(typeof value.bestPractices === "boolean" ? { bestPractices: value.bestPractices } : {}),+ ...(normalizeAgentAssistSetting(value.agentAssist) ? { agentAssist: normalizeAgentAssistSetting(value.agentAssist) } : {}),...(plugin ? { plugin } : {}),...(disabledProviders ? { disabled_providers: disabledProviders } : {}),...(mcp ? { mcp } : {}),@@ -272,6 +276,7 @@ export function mergeRuntimeOpencodeConfigLayers(// The approval mode is engine-global like the managed policy....(base.approvals ? { approvals: base.approvals } : {}),...(typeof base.bestPractices === "boolean" ? { bestPractices: base.bestPractices } : {}),+ ...(base.agentAssist ? { agentAssist: base.agentAssist } : {}),...(base.default_agent || overlay.default_agent ? { default_agent: overlay.default_agent ?? base.default_agent } : {}),...(plugin.length ? { plugin } : {}),...(disabledProviders.length ? { disabled_providers: disabledProviders } : {}),diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex f54e16b2..6a27f143 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -220,6 +220,7 @@ import { prepareDesktopInstallLog } from "./install-log-host.js";import pkg from "../package.json" with { type: "json" };import constants from "../../../constants.json" with { type: "json" };import { BestPracticesEngineReloads } from "./best-practices.js";+import { AGENT_ASSIST_FEATURES, agentAssistFlags, agentAssistForced } from "./agent-assist-config.js";import { BUNDLED_ENGINE_VERSION } from "./engine-identity.js";import { createTurnActivity, type TurnActivity } from "./turn-activity.js";@@ -4064,6 +4065,55 @@ function createRoutes(}});+ // Agent assist (agent-assist-config.ts): self-check, project notes, diagnostics, compaction.+ addRoute(routes, "GET", "/runtime-config/agent-assist", "client", async () => {+ const runtime = await readGlobalRuntimeOpencodeConfig(config);+ return jsonResponse({ features: agentAssistFlags(runtime), forced: agentAssistForced() });+ });++ addRoute(routes, "PUT", "/runtime-config/agent-assist", "client", async (ctx) => {+ ensureWritable(config);+ requireClientScope(ctx, "collaborator");+ const body = await readJsonBody(ctx.request);+ const keys = Object.keys(body);+ if (!keys.length || keys.some((key) => !(AGENT_ASSIST_FEATURES as readonly string[]).includes(key) || typeof body[key] !== "boolean")) {+ throw new ApiError(400, "invalid_payload", `send one or more of ${AGENT_ASSIST_FEATURES.join(", ")} as booleans`);+ }+ const before = agentAssistFlags(await readGlobalRuntimeOpencodeConfig(config));+ const result = await writeGlobalRuntimeOpencodeConfig(config, (current) => {+ const next: Record<string, boolean> = { ...(current.agentAssist ?? {}) };+ for (const key of keys) {+ // On is the default: only "off" is saved.+ if (body[key] === true) delete next[key];+ else next[key] = false;+ }+ const { agentAssist: _old, ...rest } = current;+ return Object.keys(next).length ? { ...rest, agentAssist: next } : rest;+ });+ const features = agentAssistFlags(await readGlobalRuntimeOpencodeConfig(config));+ const forced = agentAssistForced();+ try {+ // The plugin's switch file and the engine config; only the language servers need the engine to reload.+ await writeOmniRushRuntimeConfigFile(config);+ if (before.diagnostics === features.diagnostics) {+ return jsonResponse({ ok: true, features, forced, changed: result.changed, engine: { status: "applied" } });+ }+ const workspaces = config.workspaces.filter((workspace) => resolveWorkspaceOpencodeConnection(config, workspace).baseUrl?.trim());+ const workspace = findManagedEngineWorkspace(workspaces) ?? workspaces[0];+ if (!workspace) return jsonResponse({ ok: true, features, forced, changed: result.changed, engine: { status: "unconfigured" } });+ const pool = enginePoolForConfig(config);+ if (pool) {+ const outcome = await pool.requestRollover({ reason: "agent_assist", workspace, manual: true });+ const status = outcome.action === "coalesced" ? "deferred" : outcome.action === "skipped" ? "failed" : "applied";+ return jsonResponse({ ok: true, features, forced, changed: result.changed, engine: { status } });+ }+ const status = await bestPracticesReloads.apply(workspaces);+ return jsonResponse({ ok: true, features, forced, changed: result.changed, engine: { status } });+ } catch {+ return jsonResponse({ ok: true, features, forced, changed: result.changed, engine: { status: "failed" } });+ }+ });+addRoute(routes, "PUT", "/den-session", "host-token", async (ctx) => {ensureWritable(config);const session = parseCloudProviderDenSession(await readJsonBody(ctx.request));