Skip to content

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

Move OpenCode's discovery probe to its own file, and delete discovery sessions for every ACP engine

milind-soni080bb0750b13
diff --git a/server/drivers/acp/custom-model-catalog.test.ts b/server/drivers/acp/custom-model-catalog.test.ts
index d4ff403079..f486a85340 100644
--- a/server/drivers/acp/custom-model-catalog.test.ts
+++ b/server/drivers/acp/custom-model-catalog.test.ts
@@ -37,7 +37,8 @@ appendFileSync(process.env.CATALOG_DUMP,JSON.stringify({cwd:process.cwd(),pid:pr
for await(const line of createInterface({input:process.stdin})){
const msg=JSON.parse(line); appendFileSync(process.env.CATALOG_DUMP,JSON.stringify({cwd:process.cwd(),...msg})+'\\n');
if(!msg.method)continue;
- if(msg.method==='initialize'){emit({jsonrpc:'2.0',id:msg.id,result:{protocolVersion:1}});continue;}
+ if(msg.method==='initialize'){emit({jsonrpc:'2.0',id:msg.id,result:{protocolVersion:1,...(mode==='deletes'?{agentCapabilities:{sessionCapabilities:{delete:{}}}}:{})}});continue;}
+ if(msg.method==='session/delete'){emit({jsonrpc:'2.0',id:msg.id,result:{}});continue;}
if(msg.method==='session/new'){
if(mode==='exit'){process.exit(3);}
if(mode==='legacy'){emit({jsonrpc:'2.0',id:msg.id,result:legacyResult()});continue;}
@@ -141,6 +142,19 @@ describe("custom ACP catalog discovery (isolated fake CLI)", () => {
expect(stuck).not.toHaveBeenCalled();
});
+ it("deletes its session over ACP when the agent offers session/delete, and then skips forgetSession", async () => {
+ const fixture = await fake("deletes");
+ const forgetSession = vi.fn(async () => {});
+ await discoverAcpModels(fixture.env, fixture.config.cli, [], { forgetSession });
+ const deletes = (await fixture.requests()).filter((request) => request.method === "session/delete");
+ expect(deletes.map((request) => request.params.sessionId)).toEqual(["fake-session"]);
+ expect(forgetSession).not.toHaveBeenCalled();
+
+ const plain = await fake();
+ await discoverAcpModels(plain.env, plain.config.cli, []);
+ expect((await plain.requests()).some((request) => request.method === "session/delete")).toBe(false);
+ });
+
it("stops a custom agent at once, and lets an agent asked to exit gracefully read EOF first", async () => {
const custom = await fake();
await resolveCustomAcpModels(custom.env, custom.config);
diff --git a/server/drivers/acp/custom-model-catalog.ts b/server/drivers/acp/custom-model-catalog.ts
index f9cb5254ec..1596d58431 100644
--- a/server/drivers/acp/custom-model-catalog.ts
+++ b/server/drivers/acp/custom-model-catalog.ts
@@ -7,6 +7,7 @@ import type { ModelCatalog } from "../../contracts.ts";
import type { AcpConfig } from "./core.ts";
import { killCliTree, spawnCli } from "../../procs.ts";
import { acpModelOption, acpVariantOption } from "./config-options.ts";
+import { deleteAcpSessions, deletesAcpSessions } from "./session-delete.ts";
const REQUEST_TIMEOUT_MS = 8_000;
const DISCOVERY_TIMEOUT_MS = 60_000;
@@ -32,7 +33,7 @@ export interface AcpDiscoveryOptions {
/** Close stdin and give the agent this many milliseconds to exit on its own, so it can release what it holds,
* before it is killed. Without it the agent is killed at once. */
exitGraceMs?: number;
- /** Remove what the agent kept of the discovery session, once its process has stopped. */
+ /** Remove what the agent kept of the discovery session, once its process has stopped, when session/delete did not. */
forgetSession?(session: { sessionId: string; cwd: string; env: Record<string, string | undefined> }): Promise<void>;
}
@@ -111,6 +112,7 @@ export async function discoverAcpModels(
let sequence = 0;
let updateSequence = 0;
let sessionId: string | undefined;
+ let initialized: unknown;
let latestUpdate: unknown;
let outputBytes = 0;
let buffer = "";
@@ -189,7 +191,7 @@ export async function discoverAcpModels(
});
child.stderr.on("data", (chunk: Buffer) => { count(chunk); });
globalTimer = setTimeout(() => fail("ACP model discovery timed out."), DISCOVERY_TIMEOUT_MS);
- await request("initialize", {
+ initialized = await request("initialize", {
protocolVersion: 1,
clientInfo: { name: DISCOVERY_CLIENT_NAME, version: "1" },
clientCapabilities: {
@@ -252,11 +254,12 @@ export async function discoverAcpModels(
thrown = error;
} finally {
if (globalTimer) clearTimeout(globalTimer);
+ const deleted = sessionId && deletesAcpSessions(initialized) ? (await deleteAcpSessions(request, [sessionId])).length > 0 : false;
fail("ACP model discovery finished.");
let stopped = false;
try {
stopped = await stopDiscovery(child, discovery.exitGraceMs);
- if (stopped && sessionId) await discovery.forgetSession?.({ sessionId, cwd, env }).catch(() => undefined);
+ if (stopped && sessionId && !deleted) await discovery.forgetSession?.({ sessionId, cwd, env }).catch(() => undefined);
} finally {
await rm(cwd, { recursive: true, force: true });
}
diff --git a/server/drivers/acp/opencode-go.ts b/server/drivers/acp/opencode-go.ts
index 2f248862e3..8abbe69435 100644
--- a/server/drivers/acp/opencode-go.ts
+++ b/server/drivers/acp/opencode-go.ts
@@ -1,10 +1,8 @@
// OpenCode over ACP; Zen, Go, OpenRouter and local providers are models it discovers, not separate drivers.
-import { execFile } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, isAbsolute, join, relative, resolve as resolvePath, sep } from "node:path";
-import { writeFileAtomic } from "../../atomic.ts";
import { ATTACHMENTS_DIR } from "../../attachments.ts";
import { cloudHomeConfigured } from "../../cloud-home.ts";
import { DATA_DIR, OPENCODE_PROVIDER_ENV } from "../../config.ts";
@@ -13,7 +11,7 @@ import { decodeInjectId, hostApiKey, localHost, mergeLocalInject } from "../loca
import { applyStandaloneSpawnEnv } from "../../engine-install.ts";
import { OPENCODE_STANDALONE } from "./opencode-release.ts";
import { createAcpDriver, type AccountErrorCode, type AcpConfig, type AcpSupport } from "./core.ts";
-import { offeredModels, surveyModelVariants } from "./config-options.ts";
+import { offeredModels } from "./config-options.ts";
import { declareTypedOpenCodeModel } from "./opencode-typed-model.ts";
import {
declareLiveOpenCodeModels,
@@ -26,8 +24,19 @@ import {
} from "./opencode-model-refresh.ts";
import { parseOpenCodeLogLine } from "./quiet-status.ts";
import type { ModelCatalog, ModelVariantOption, ProviderDriver, ProviderErrorCode } from "../../contracts.ts";
-import { titleCaseModelId } from "../../contracts.ts";
-import { execCli, killCliTree, spawnCli } from "../../procs.ts";
+import { execCli } from "../../procs.ts";
+import {
+ catalogFromOpenCodeSession,
+ DISCOVERY_TIMEOUT_MS,
+ discoveryDirectory,
+ forgetDiscoveryDirectory,
+ labelForModel,
+ probeOpenCodeSession,
+ providerLabel,
+ validModelSlug,
+} from "./opencode-probe.ts";
+
+export { catalogFromOpenCodeSession, surveyOpenCodeEfforts } from "./opencode-probe.ts";
const NO_MODELS: ModelCatalog = { default: "", options: [] };
@@ -37,8 +46,6 @@ const catalogRevisions = new Map<string, number>();
const freeModels = new Set<string>();
const paidModels = new Set<string>();
-const DISCOVERY_TIMEOUT_MS = 20_000;
-const EFFORT_SURVEY_MS = 8_000;
const DISCOVERY_PROBE_TTL_MS = 30_000;
/** How long a listing OpenCode 2 runs stays open for its own catalog refresh to land (2.2.5 fetched 11 MB in 4 s). */
const SELF_REFRESH_SETTLE_MS = 10_000;
@@ -50,23 +57,6 @@ export type OpenCodeCatalogLoader = (
options?: { refresh?: boolean; settleMs?: number },
) => Promise<ModelCatalog>;
-function labelForModel(id: string): string {
- return titleCaseModelId(id, /[-_.]+/);
-}
-
-function providerLabel(id: string): string {
- if (id === "opencode") return "Zen";
- if (id === "opencode-go") return "Go";
- if (id === "openrouter") return "OpenRouter";
- return labelForModel(id);
-}
-
-function validModelSlug(value: string): boolean {
- const separator = value.indexOf("/");
- if (separator <= 0 || separator >= value.length - 1 || /\s/u.test(value)) return false;
- return [...value].every((character) => (character.codePointAt(0) ?? 0) > 0x1f);
-}
-
function localModelRecord(record: Record<string, unknown>): boolean {
const api = record.api && typeof record.api === "object" && !Array.isArray(record.api)
? record.api as Record<string, unknown>
@@ -190,36 +180,6 @@ export function parseOpenCodeModelsOutput(stdout: string): ModelCatalog | null {
rememberPrices(parsed);
return { default: preferredOpenCodeModel(parsed.options.map((option) => option.id)), options: parsed.options };
}
-
-/** The `model` select in session/new's configOptions: exactly what set_config_option accepts, and the only reliable list on V2. */
-export function catalogFromOpenCodeSession(result: unknown): { options: ModelCatalog["options"]; current: string | null } | null {
- const configOptions = (result as { configOptions?: unknown } | null)?.configOptions;
- const model = Array.isArray(configOptions)
- ? configOptions.find((option: any) => option?.id === "model" && option?.type === "select")
- : null;
- const ids = offeredModels(result, "model");
- if (!model || !ids.length) return null;
- const names = new Map<string, string>();
- const visit = (entries: unknown) => {
- if (!Array.isArray(entries)) return;
- for (const entry of entries) {
- if (typeof entry?.value === "string" && typeof entry.name === "string") names.set(entry.value, entry.name);
- else if (Array.isArray(entry?.options)) visit(entry.options);
- }
- };
- visit(model.options);
- const options = [...new Set(ids)].filter(validModelSlug).map((id) => {
- const separator = id.indexOf("/");
- // V1 names "OpenCode Zen/Big Pickle", V2 "opencode/Big Pickle": the provider comes from the id.
- const raw = names.get(id)?.trim() ?? "";
- const name = (raw.includes("/") ? raw.slice(raw.indexOf("/") + 1) : raw).trim() || labelForModel(id.slice(separator + 1));
- return { id, label: `${providerLabel(id.slice(0, separator))} · ${name}` };
- });
- return options.length
- ? { options, current: typeof (model as any).currentValue === "string" ? (model as any).currentValue : null }
- : null;
-}
-
function runOpenCodeModelsVerbose(
cli: string,
environment: Record<string, string | undefined>,
@@ -259,223 +219,6 @@ function sameModelIds(left: ModelCatalog | undefined, right: ModelCatalog): bool
return ids.size === right.options.length && right.options.every((option) => ids.has(option.id));
}
-function runGit(directory: string, args: string[]): Promise<void> {
- const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_")));
- return new Promise((resolveRun, rejectRun) => {
- execFile("git", [
- "-c", "user.name=OpenMaus", "-c", "[email protected]",
- "-c", "commit.gpgsign=false", "-c", `core.hooksPath=${join(directory, ".git", "no-hooks")}`,
- ...args,
- ], { cwd: directory, env: { ...env, GIT_TERMINAL_PROMPT: "0" }, timeout: 10_000, windowsHide: true }, (error) => {
- if (error) rejectRun(error);
- else resolveRun();
- });
- });
-}
-
-let discoveryFolder: Promise<string> | null = null;
-
-/** OpenCode files every session under its working folder's project, and folders outside git share one
- * global project, so `opencode run --continue` there would resume the probe's empty session. */
-function discoveryDirectory(): Promise<string> {
- discoveryFolder ??= (async () => {
- const directory = join(DATA_DIR, "providers", "opencode", "discovery");
- mkdirSync(directory, { recursive: true });
- const marker = join(directory, ".openmaus-project");
- if (!existsSync(marker)) {
- try {
- await runGit(directory, ["init", "-q"]);
- await runGit(directory, ["commit", "-q", "--allow-empty", "--no-verify", "-m", "OpenMaus model discovery"]);
- writeFileSync(marker, "OpenCode files this folder's sessions under its own project.\n");
- } catch {}
- }
- return directory;
- })();
- return discoveryFolder;
-}
-
-export interface OpenCodeSessionProbe {
- session: unknown;
- /** Each surveyed model's ACP effort choices; an empty list means it has none. */
- efforts: Map<string, ModelVariantOption[]>;
-}
-
-/** OpenCode (1.18.27, 1.19.4, 2.1.4) names a model's efforts only in the session's `effort` option once that
- * model is selected, and OpenCode 2.1.4 answers overlapping selections with another model's options. */
-export function surveyOpenCodeEfforts(
- request: (method: string, params: unknown) => Promise<unknown>,
- session: unknown,
- budgetMs = EFFORT_SURVEY_MS,
-): Promise<Map<string, ModelVariantOption[]>> {
- return surveyModelVariants(request, session, budgetMs);
-}
-
-/** Session id -> when a probe opened it. Only ids in here are ever deleted, so another client's sessions in the
- * discovery folder survive; a probe cut off by its timeout leaves its ids for the next probe to delete. */
-type ProbeSessionLedger = Record<string, number>;
-
-const probeLedgerPath = (cwd: string) => join(cwd, ".openmaus-probe-sessions.json");
-
-function readProbeLedger(cwd: string): ProbeSessionLedger {
- try {
- const ledger: unknown = JSON.parse(readFileSync(probeLedgerPath(cwd), "utf8"));
- return ledger && typeof ledger === "object" && !Array.isArray(ledger) ? ledger as ProbeSessionLedger : {};
- } catch {
- return {};
- }
-}
-
-function changeProbeLedger(cwd: string, change: (ledger: ProbeSessionLedger) => void): void {
- const ledger = readProbeLedger(cwd);
- change(ledger);
- try {
- writeFileAtomic(probeLedgerPath(cwd), JSON.stringify(ledger), { durable: false });
- } catch {}
-}
-
-/** OpenCode (2.2.0, 2.2.6) keeps every ACP session, even one closed with session/close or whose process was killed,
- * and lists it in the user's history; only session/delete removes it, and it answers {} for an id it does not know. */
-async function deleteProbeSessions(
- request: (method: string, params: unknown) => Promise<unknown>,
- cwd: string,
- opened: string[],
- timeoutMs: number,
-): Promise<void> {
- const abandonedBefore = Date.now() - 2 * timeoutMs;
- const abandoned = Object.entries(readProbeLedger(cwd))
- .filter(([, openedAt]) => openedAt < abandonedBefore)
- .map(([sessionId]) => sessionId);
- await Promise.all([...new Set([...opened, ...abandoned])].map((sessionId) => request("session/delete", { sessionId }).then(
- () => changeProbeLedger(cwd, (ledger) => delete ledger[sessionId]),
- () => {},
- )));
-}
-
-/** `settleMs` keeps the process open that long after it starts, then lists again: OpenCode 2's own catalog refresh
- * reaches a running process's later sessions only. */
-export async function probeOpenCodeSession(
- cli: string,
- environment: Record<string, string | undefined>,
- timeoutMs = DISCOVERY_TIMEOUT_MS,
- settleMs = 0,
-): Promise<OpenCodeSessionProbe> {
- const cwd = await discoveryDirectory();
- const deadline = Date.now() + timeoutMs;
- return new Promise((resolve, reject) => {
- let child: ReturnType<typeof spawnCli>;
- try {
- child = spawnCli(cli, ["acp"], { cwd, env: environment, stdio: ["pipe", "pipe", "pipe"] });
- } catch (error) {
- reject(error);
- return;
- }
- let settled = false;
- let listed: OpenCodeSessionProbe | undefined;
- let buffer = "";
- let nextId = 0;
- const pending = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();
- const write = (message: unknown) => {
- try {
- child.stdin.write(`${JSON.stringify(message)}\n`);
- } catch {}
- };
- const finish = (error: Error | null, value?: OpenCodeSessionProbe) => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- try {
- child.stdin.end();
- } catch {}
- void killCliTree(child);
- for (const waiter of pending.values()) waiter.reject(new Error("OpenCode closed"));
- pending.clear();
- const result = value ?? listed;
- if (result) resolve(result);
- else reject(error ?? new Error("OpenCode did not list its models"));
- };
- const timer = setTimeout(
- () => finish(Object.assign(new Error("OpenCode did not list its models in time"), { timedOut: true })),
- timeoutMs,
- );
- timer.unref?.();
- child.on("error", (error) => finish(error));
- child.on("close", (code) => finish(new Error(`OpenCode exited ${code} while listing its models`)));
- child.stderr.resume();
- child.stdout.setEncoding("utf8");
- child.stdout.on("data", (chunk: string) => {
- buffer += chunk;
- let newline: number;
- while ((newline = buffer.indexOf("\n")) !== -1) {
- const line = buffer.slice(0, newline);
- buffer = buffer.slice(newline + 1);
- let message: any;
- try {
- message = JSON.parse(line);
- } catch {
- continue;
- }
- if (message?.id !== undefined && typeof message.method === "string") {
- write({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "method not found" } });
- continue;
- }
- const waiter = typeof message?.id === "number" ? pending.get(message.id) : undefined;
- if (!waiter) continue;
- pending.delete(message.id);
- if (message.error) {
- waiter.reject(Object.assign(new Error(String(message.error.message ?? "ACP request failed")), {
- code: message.error.code,
- data: message.error.data,
- }));
- } else waiter.resolve(message.result);
- }
- });
- const request = (method: string, params: unknown) => new Promise<unknown>((resolveRequest, rejectRequest) => {
- if (settled) {
- rejectRequest(new Error("OpenCode closed"));
- return;
- }
- const id = ++nextId;
- pending.set(id, { resolve: resolveRequest, reject: rejectRequest });
- write({ jsonrpc: "2.0", id, method, params });
- });
- let deletesSessions = false;
- const opened: string[] = [];
- const openSession = async () => {
- const session = await request("session/new", { cwd, mcpServers: [] });
- const sessionId = (session as { sessionId?: unknown } | null)?.sessionId;
- if (deletesSessions && typeof sessionId === "string") {
- opened.push(sessionId);
- changeProbeLedger(cwd, (ledger) => { ledger[sessionId] = Date.now(); });
- }
- return session;
- };
- const cleanUp = () => deletesSessions ? deleteProbeSessions(request, cwd, opened, timeoutMs) : Promise.resolve();
- void (async () => {
- const initialized = await request("initialize", {
- protocolVersion: 1,
- clientInfo: { name: "openmausbot", version: "0.0.0" },
- clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
- }) as { agentCapabilities?: { sessionCapabilities?: { delete?: unknown } } } | null;
- deletesSessions = Boolean(initialized?.agentCapabilities?.sessionCapabilities?.delete);
- const session = await openSession();
- listed = { session, efforts: new Map() };
- const budget = Math.min(EFFORT_SURVEY_MS, deadline - Date.now() - 1_000);
- const efforts = await surveyOpenCodeEfforts(request, session, budget);
- if (!settleMs) return { session, efforts };
- const wait = Math.min(settleMs, timeoutMs - 2_000) - (Date.now() - (deadline - timeoutMs));
- if (wait > 0) await new Promise((resolveWait) => setTimeout(resolveWait, wait));
- const later = await openSession();
- return { session: catalogFromOpenCodeSession(later) ? later : session, efforts };
- })().then(
- (result) => {
- listed = result;
- return cleanUp().then(() => finish(null, result));
- },
- (error: Error) => cleanUp().then(() => finish(error)),
- );
- });
-}
-
/** The session's own effort choices win over `models --verbose`: they are what set_config_option accepts. */
function withEfforts(
option: ModelCatalog["options"][number],
@@ -555,7 +298,7 @@ export async function canRunOpenCode(
}
export function resetOpenCodeModelCache() {
- discoveryFolder = null;
+ forgetDiscoveryDirectory();
resetLiveModelLists();
lastSuccessfulCatalog.clear();
catalogRevisions.clear();
diff --git a/server/drivers/acp/opencode-probe.ts b/server/drivers/acp/opencode-probe.ts
new file mode 100644
index 0000000000..444264a743
--- /dev/null
+++ b/server/drivers/acp/opencode-probe.ts
@@ -0,0 +1,279 @@
+// OpenCode's model discovery probe: an `opencode acp` in its own folder, opened just long enough to list the models.
+import { execFile } from "node:child_process";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { writeFileAtomic } from "../../atomic.ts";
+import { DATA_DIR } from "../../config.ts";
+import { titleCaseModelId, type ModelCatalog, type ModelVariantOption } from "../../contracts.ts";
+import { killCliTree, spawnCli } from "../../procs.ts";
+import { offeredModels, surveyModelVariants } from "./config-options.ts";
+import { deleteAcpSessions, deletesAcpSessions } from "./session-delete.ts";
+
+export const DISCOVERY_TIMEOUT_MS = 20_000;
+const EFFORT_SURVEY_MS = 8_000;
+
+export function labelForModel(id: string): string {
+ return titleCaseModelId(id, /[-_.]+/);
+}
+
+export function providerLabel(id: string): string {
+ if (id === "opencode") return "Zen";
+ if (id === "opencode-go") return "Go";
+ if (id === "openrouter") return "OpenRouter";
+ return labelForModel(id);
+}
+
+export function validModelSlug(value: string): boolean {
+ const separator = value.indexOf("/");
+ if (separator <= 0 || separator >= value.length - 1 || /\s/u.test(value)) return false;
+ return [...value].every((character) => (character.codePointAt(0) ?? 0) > 0x1f);
+}
+
+/** The `model` select in session/new's configOptions: exactly what set_config_option accepts, and the only reliable list on V2. */
+export function catalogFromOpenCodeSession(result: unknown): { options: ModelCatalog["options"]; current: string | null } | null {
+ const configOptions = (result as { configOptions?: unknown } | null)?.configOptions;
+ const model = Array.isArray(configOptions)
+ ? configOptions.find((option: any) => option?.id === "model" && option?.type === "select")
+ : null;
+ const ids = offeredModels(result, "model");
+ if (!model || !ids.length) return null;
+ const names = new Map<string, string>();
+ const visit = (entries: unknown) => {
+ if (!Array.isArray(entries)) return;
+ for (const entry of entries) {
+ if (typeof entry?.value === "string" && typeof entry.name === "string") names.set(entry.value, entry.name);
+ else if (Array.isArray(entry?.options)) visit(entry.options);
+ }
+ };
+ visit(model.options);
+ const options = [...new Set(ids)].filter(validModelSlug).map((id) => {
+ const separator = id.indexOf("/");
+ // V1 names "OpenCode Zen/Big Pickle", V2 "opencode/Big Pickle": the provider comes from the id.
+ const raw = names.get(id)?.trim() ?? "";
+ const name = (raw.includes("/") ? raw.slice(raw.indexOf("/") + 1) : raw).trim() || labelForModel(id.slice(separator + 1));
+ return { id, label: `${providerLabel(id.slice(0, separator))} · ${name}` };
+ });
+ return options.length
+ ? { options, current: typeof (model as any).currentValue === "string" ? (model as any).currentValue : null }
+ : null;
+}
+
+function runGit(directory: string, args: string[]): Promise<void> {
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_")));
+ return new Promise((resolveRun, rejectRun) => {
+ execFile("git", [
+ "-c", "user.name=OpenMaus", "-c", "[email protected]",
+ "-c", "commit.gpgsign=false", "-c", `core.hooksPath=${join(directory, ".git", "no-hooks")}`,
+ ...args,
+ ], { cwd: directory, env: { ...env, GIT_TERMINAL_PROMPT: "0" }, timeout: 10_000, windowsHide: true }, (error) => {
+ if (error) rejectRun(error);
+ else resolveRun();
+ });
+ });
+}
+
+let discoveryFolder: Promise<string> | null = null;
+
+export function forgetDiscoveryDirectory(): void {
+ discoveryFolder = null;
+}
+
+/** OpenCode files every session under its working folder's project, and folders outside git share one
+ * global project, so `opencode run --continue` there would resume the probe's empty session. */
+export function discoveryDirectory(): Promise<string> {
+ discoveryFolder ??= (async () => {
+ const directory = join(DATA_DIR, "providers", "opencode", "discovery");
+ mkdirSync(directory, { recursive: true });
+ const marker = join(directory, ".openmaus-project");
+ if (!existsSync(marker)) {
+ try {
+ await runGit(directory, ["init", "-q"]);
+ await runGit(directory, ["commit", "-q", "--allow-empty", "--no-verify", "-m", "OpenMaus model discovery"]);
+ writeFileSync(marker, "OpenCode files this folder's sessions under its own project.\n");
+ } catch {}
+ }
+ return directory;
+ })();
+ return discoveryFolder;
+}
+
+export interface OpenCodeSessionProbe {
+ session: unknown;
+ /** Each surveyed model's ACP effort choices; an empty list means it has none. */
+ efforts: Map<string, ModelVariantOption[]>;
+}
+
+/** OpenCode (1.18.27, 1.19.4, 2.1.4) names a model's efforts only in the session's `effort` option once that
+ * model is selected, and OpenCode 2.1.4 answers overlapping selections with another model's options. */
+export function surveyOpenCodeEfforts(
+ request: (method: string, params: unknown) => Promise<unknown>,
+ session: unknown,
+ budgetMs = EFFORT_SURVEY_MS,
+): Promise<Map<string, ModelVariantOption[]>> {
+ return surveyModelVariants(request, session, budgetMs);
+}
+
+/** Session id -> when a probe opened it. Only ids in here are ever deleted, so another client's sessions in the
+ * discovery folder survive; a probe cut off by its timeout leaves its ids for the next probe to delete. */
+type ProbeSessionLedger = Record<string, number>;
+
+const probeLedgerPath = (cwd: string) => join(cwd, ".openmaus-probe-sessions.json");
+
+function readProbeLedger(cwd: string): ProbeSessionLedger {
+ try {
+ const ledger: unknown = JSON.parse(readFileSync(probeLedgerPath(cwd), "utf8"));
+ return ledger && typeof ledger === "object" && !Array.isArray(ledger) ? ledger as ProbeSessionLedger : {};
+ } catch {
+ return {};
+ }
+}
+
+function changeProbeLedger(cwd: string, change: (ledger: ProbeSessionLedger) => void): void {
+ const ledger = readProbeLedger(cwd);
+ change(ledger);
+ try {
+ writeFileAtomic(probeLedgerPath(cwd), JSON.stringify(ledger), { durable: false });
+ } catch {}
+}
+
+/** OpenCode (2.2.0, 2.2.6) keeps every ACP session, even one closed with session/close or whose process was killed,
+ * and lists it in the user's history; only session/delete removes it, and it answers {} for an id it does not know. */
+async function deleteProbeSessions(
+ request: (method: string, params: unknown) => Promise<unknown>,
+ cwd: string,
+ opened: string[],
+ timeoutMs: number,
+): Promise<void> {
+ const abandonedBefore = Date.now() - 2 * timeoutMs;
+ const abandoned = Object.entries(readProbeLedger(cwd))
+ .filter(([, openedAt]) => openedAt < abandonedBefore)
+ .map(([sessionId]) => sessionId);
+ const deleted = await deleteAcpSessions(request, [...opened, ...abandoned]);
+ if (deleted.length) changeProbeLedger(cwd, (ledger) => { for (const sessionId of deleted) delete ledger[sessionId]; });
+}
+
+/** `settleMs` keeps the process open that long after it starts, then lists again: OpenCode 2's own catalog refresh
+ * reaches a running process's later sessions only. */
+export async function probeOpenCodeSession(
+ cli: string,
+ environment: Record<string, string | undefined>,
+ timeoutMs = DISCOVERY_TIMEOUT_MS,
+ settleMs = 0,
+): Promise<OpenCodeSessionProbe> {
+ const cwd = await discoveryDirectory();
+ const deadline = Date.now() + timeoutMs;
+ return new Promise((resolve, reject) => {
+ let child: ReturnType<typeof spawnCli>;
+ try {
+ child = spawnCli(cli, ["acp"], { cwd, env: environment, stdio: ["pipe", "pipe", "pipe"] });
+ } catch (error) {
+ reject(error);
+ return;
+ }
+ let settled = false;
+ let listed: OpenCodeSessionProbe | undefined;
+ let buffer = "";
+ let nextId = 0;
+ const pending = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();
+ const write = (message: unknown) => {
+ try {
+ child.stdin.write(`${JSON.stringify(message)}\n`);
+ } catch {}
+ };
+ const finish = (error: Error | null, value?: OpenCodeSessionProbe) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ try {
+ child.stdin.end();
+ } catch {}
+ void killCliTree(child);
+ for (const waiter of pending.values()) waiter.reject(new Error("OpenCode closed"));
+ pending.clear();
+ const result = value ?? listed;
+ if (result) resolve(result);
+ else reject(error ?? new Error("OpenCode did not list its models"));
+ };
+ const timer = setTimeout(
+ () => finish(Object.assign(new Error("OpenCode did not list its models in time"), { timedOut: true })),
+ timeoutMs,
+ );
+ timer.unref?.();
+ child.on("error", (error) => finish(error));
+ child.on("close", (code) => finish(new Error(`OpenCode exited ${code} while listing its models`)));
+ child.stderr.resume();
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => {
+ buffer += chunk;
+ let newline: number;
+ while ((newline = buffer.indexOf("\n")) !== -1) {
+ const line = buffer.slice(0, newline);
+ buffer = buffer.slice(newline + 1);
+ let message: any;
+ try {
+ message = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ if (message?.id !== undefined && typeof message.method === "string") {
+ write({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "method not found" } });
+ continue;
+ }
+ const waiter = typeof message?.id === "number" ? pending.get(message.id) : undefined;
+ if (!waiter) continue;
+ pending.delete(message.id);
+ if (message.error) {
+ waiter.reject(Object.assign(new Error(String(message.error.message ?? "ACP request failed")), {
+ code: message.error.code,
+ data: message.error.data,
+ }));
+ } else waiter.resolve(message.result);
+ }
+ });
+ const request = (method: string, params: unknown) => new Promise<unknown>((resolveRequest, rejectRequest) => {
+ if (settled) {
+ rejectRequest(new Error("OpenCode closed"));
+ return;
+ }
+ const id = ++nextId;
+ pending.set(id, { resolve: resolveRequest, reject: rejectRequest });
+ write({ jsonrpc: "2.0", id, method, params });
+ });
+ let deletesSessions = false;
+ const opened: string[] = [];
+ const openSession = async () => {
+ const session = await request("session/new", { cwd, mcpServers: [] });
+ const sessionId = (session as { sessionId?: unknown } | null)?.sessionId;
+ if (deletesSessions && typeof sessionId === "string") {
+ opened.push(sessionId);
+ changeProbeLedger(cwd, (ledger) => { ledger[sessionId] = Date.now(); });
+ }
+ return session;
+ };
+ const cleanUp = () => deletesSessions ? deleteProbeSessions(request, cwd, opened, timeoutMs) : Promise.resolve();
+ void (async () => {
+ const initialized = await request("initialize", {
+ protocolVersion: 1,
+ clientInfo: { name: "openmausbot", version: "0.0.0" },
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
+ });
+ deletesSessions = deletesAcpSessions(initialized);
+ const session = await openSession();
+ listed = { session, efforts: new Map() };
+ const budget = Math.min(EFFORT_SURVEY_MS, deadline - Date.now() - 1_000);
+ const efforts = await surveyOpenCodeEfforts(request, session, budget);
+ if (!settleMs) return { session, efforts };
+ const wait = Math.min(settleMs, timeoutMs - 2_000) - (Date.now() - (deadline - timeoutMs));
+ if (wait > 0) await new Promise((resolveWait) => setTimeout(resolveWait, wait));
+ const later = await openSession();
+ return { session: catalogFromOpenCodeSession(later) ? later : session, efforts };
+ })().then(
+ (result) => {
+ listed = result;
+ return cleanUp().then(() => finish(null, result));
+ },
+ (error: Error) => cleanUp().then(() => finish(error)),
+ );
+ });
+}
diff --git a/server/drivers/acp/session-delete.ts b/server/drivers/acp/session-delete.ts
new file mode 100644
index 0000000000..0c37caf947
--- /dev/null
+++ b/server/drivers/acp/session-delete.ts
@@ -0,0 +1,19 @@
+// Model discovery opens ACP sessions only to read their model lists. An agent that keeps every session (OpenCode
+// 2.2.0 and 2.2.6 keep one even after session/close or a killed process) lists them in the person's history, so
+// discovery deletes its own sessions whenever the agent offers session/delete.
+
+/** True when the answer to initialize advertises session/delete. */
+export function deletesAcpSessions(initialized: unknown): boolean {
+ const agent = (initialized as { agentCapabilities?: { sessionCapabilities?: { delete?: unknown } } } | null)?.agentCapabilities;
+ return Boolean(agent?.sessionCapabilities?.delete);
+}
+
+/** Sends session/delete for each id and answers the ids the agent confirmed. */
+export async function deleteAcpSessions(
+ request: (method: string, params: unknown) => Promise<unknown>,
+ sessionIds: Iterable<string>,
+): Promise<string[]> {
+ const ids = [...new Set(sessionIds)];
+ const answers = await Promise.allSettled(ids.map((sessionId) => request("session/delete", { sessionId })));
+ return ids.filter((_, index) => answers[index]?.status === "fulfilled");
+}