feat(server): add Oh My Pi (omp) as an ACP provider #10893
Closedomnificate(GitHub profile, opens in a new tab)wants to merge 1 commit into
main fromrefs/pull/10893/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -220,3 +221,4 @@220221 [CLAUDE_DRIVER_KIND]: "Claude",221222 [CURSOR_DRIVER_KIND]: "Cursor",222223 [GROK_DRIVER_KIND]: "Grok",224+ [OMP_DRIVER_KIND]: "Oh My Pi",@@ -0,0 +1534,21 @@1534+ return c !== undefined && !c.stopped;1535+ });1536+1537+ const stopAll: OmpAdapterShape["stopAll"] = () =>1538+ Effect.forEach(sessions.values(), stopSessionInternal, { discard: true });1539+1540+ yield* Effect.addFinalizer(() =>1541+ Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe(1542+ Effect.catch((cause) =>1543+ Effect.logError("Failed to emit Oh My Pi session shutdown event.", { cause }),1544+ ),1545+ Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),1546+ Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),1547+ ),1548+ );1549+1550+ const streamEvents = Stream.fromPubSub(runtimeEventPubSub);1551+1552+ return {1553+ provider: PROVIDER,1554+ capabilities: { sessionModelSwitch: "in-session" },@@ -0,0 +359,21 @@359+ const modelOption = findOmpModelConfigOption(configOptions ?? []);360+ if (!modelOption) {361+ return [];362+ }363+ const capabilities = buildOmpCapabilitiesFromConfigOptions(configOptions);364+ const seen = new Set<string>();365+ const models = flattenSessionConfigSelectOptions(modelOption).flatMap((entry) => {366+ if (!entry.value || seen.has(entry.value)) {367+ return [];368+ }369+ seen.add(entry.value);370+ const slashIndex = entry.value.indexOf("/");371+ const subProvider =372+ slashIndex > 0 ? titleCaseSlug(entry.value.slice(0, slashIndex)) : undefined;373+ return [374+ {375+ slug: entry.value,376+ name: entry.name || entry.value,377+ ...(subProvider ? { subProvider } : {}),378+ isCustom: false,379+ capabilities,@@ -0,0 +127,21 @@127+ * current config value wins.128+ */129+export function applyOmpAcpModelSelection<E>(input: {130+ readonly runtime: OmpAcpModelSelectionRuntime;131+ readonly model: string | null | undefined;132+ readonly selections: ReadonlyArray<ProviderOptionSelection> | null | undefined;133+ readonly mapError: (context: OmpAcpModelSelectionErrorContext) => E;134+}): Effect.Effect<void, E> {135+ return Effect.gen(function* () {136+ const requestedModel = resolveOmpAcpBaseModelId(input.model);137+ // Model first, then re-read config options: omp re-validates dependent138+ // selects per model (e.g. `thinking` accepts off/auto under `auto` but139+ // off/low/medium/high/max elsewhere), so validating against the140+ // pre-switch options writes values the session then rejects.141+ if (requestedModel !== undefined) {142+ const configOptions = yield* input.runtime.getConfigOptions;143+ const modelConfigId =144+ configOptions.find((option) => option.category?.trim().toLowerCase() === "model")?.id ??145+ configOptions.find((option) => option.id.trim().toLowerCase() === "model")?.id ??146+ "model";147+ yield* input.runtime
- apps/server/src/provider/Layers/OmpAdapter.ts line 1359OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1339,21 @@1339+ mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),1340+ ),1341+ );1342+1343+ const turnRecord = ctx.turns.find((turn) => turn.id === turnId);1344+ if (turnRecord) {1345+ turnRecord.items.push({ prompt: promptParts, result });1346+ } else {1347+ ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });1348+ }1349+ ctx.session = {1350+ ...ctx.session,1351+ activeTurnId: turnId,1352+ updatedAt: yield* nowIso,1353+ ...(resolvedModel ? { model: resolvedModel } : {}),1354+ };1355+1356+ // Only the last remaining prompt settles the turn — a steer-1357+ // superseded prompt resolving (usually cancelled) while another is1358+ // in flight or pending must leave the merged turn running.1359+ if (ctx.promptsInFlight === 1) {apps/server/src/textGeneration/OmpTextGeneration.test.ts lines 93 to 97Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +77,21 @@77+ const agentPath = makeAcpAgentWrapper(tempDir, env, argvLogPath);78+ const config = decodeOmpSettings({ binaryPath: agentPath });79+ const textGeneration = yield* makeOmpTextGeneration(config);80+ return yield* effectFn(textGeneration);81+ }).pipe(Effect.scoped);82+}83+84+function waitForFileContent(path: string): Effect.Effect<string> {85+ return Effect.gen(function* () {86+ const deadline = (yield* Clock.currentTimeMillis) + 5_000;87+ for (;;) {88+ const result = yield* Effect.exit(Effect.sync(() => NodeFS.readFileSync(path, "utf8")));89+ if (Exit.isSuccess(result)) {90+ return result.value;91+ }92+ {93+ if ((yield* Clock.currentTimeMillis) >= deadline) {94+ return yield* Effect.die(result.cause);95+ }96+ }97+ yield* Effect.sleep(25);
- apps/server/src/provider/acp/OmpAcpSupport.ts lines 127 to 134OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +114,21 @@114+ return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(115+ Effect.provide(acpContext),116+ );117+ });118+119+interface OmpAcpModelSelectionRuntime {120+ readonly getConfigOptions: AcpSessionRuntime.AcpSessionRuntime["Service"]["getConfigOptions"];121+ readonly setConfigOption: (122+ configId: string,123+ value: string | boolean,124+ ) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;125+}126+127+function findOmpModelConfigOption(128+ configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,129+): EffectAcpSchema.SessionConfigOption | undefined {130+ return (131+ configOptions.find((option) => option.category?.trim().toLowerCase() === "model") ??132+ configOptions.find((option) => option.id.trim().toLowerCase() === "model")133+ );134+}apps/server/src/provider/Layers/OmpProvider.ts line 369OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +349,21 @@349+/**350+ * Oh My Pi is a meta provider (like OpenCode): model ids advertised through351+ * the ACP `model` config option are `provider/model` pairs routed to upstream352+ * providers the user configured inside omp. Mirror OpenCode's presentation353+ * by surfacing the upstream provider as `subProvider` and sorting the catalog354+ * by display name so the picker stays usable with 100+ entries.355+ */356+function buildOmpDiscoveredModelsFromConfigOptions(357+ configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,358+): ReadonlyArray<ServerProviderModel> {359+ const modelOption = findOmpModelConfigOption(configOptions ?? []);360+ if (!modelOption) {361+ return [];362+ }363+ // The probe session's configOptions describe the model it currently has364+ // selected (omp re-validates dependent options per model). Advertising365+ // those capabilities for every catalog entry would offer invalid366+ // reasoning choices on other models, so only the probed model carries367+ // them; the rest report null and the adapter re-reads options per model368+ // at selection time.369+ const currentModelId = modelOption.type === "select" ? modelOption.currentValue : undefined;
- apps/server/src/provider/Layers/OmpProvider.ts lines 265 to 280Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +260,21 @@260+ : [];261+262+ const contextOption = configOptions.find(263+ (option) => option.category === "model_config" && isOmpContextConfigOption(option),264+ );265+ const contextWindowOptions =266+ contextOption?.type === "select"267+ ? flattenSessionConfigSelectOptions(contextOption).map((entry) => {268+ if (contextOption.currentValue === entry.value) {269+ return {270+ value: entry.value,271+ label: entry.name,272+ isDefault: true,273+ };274+ }275+ return {276+ value: entry.value,277+ label: entry.name,278+ };279+ })280+ : [];
- @@ -0,0 +137,21 @@137+ readonly selections: ReadonlyArray<ProviderOptionSelection> | null | undefined;138+ readonly mapError: (context: OmpAcpModelSelectionErrorContext) => E;139+}): Effect.Effect<{ readonly model: string | undefined }, E> {140+ return Effect.gen(function* () {141+ const requestedModel = resolveOmpAcpBaseModelId(input.model);142+ let effectiveModel = requestedModel;143+ // Model first, then re-read config options: omp re-validates dependent144+ // selects per model (e.g. `thinking` accepts off/auto under `auto` but145+ // off/low/medium/high/max elsewhere), so validating against the146+ // pre-switch options writes values the session then rejects.147+ if (requestedModel !== undefined) {148+ const configOptions = yield* input.runtime.getConfigOptions;149+ // Existence probe without the select guard: ACP permits a boolean150+ // option named `model`, and a string slug must never be written to it.151+ const anyModelOption = configOptions.find(152+ (option) =>153+ option.category?.trim().toLowerCase() === "model" ||154+ option.id.trim().toLowerCase() === "model",155+ );156+ const modelOption = findOmpModelConfigOption(configOptions);157+ const modelConfigId = anyModelOption?.id ?? "model";apps/server/src/provider/Layers/OmpAdapter.test.ts lines 115 to 128Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +108,21 @@108+ return raw109+ .split("\n")110+ .map((line) => line.trim())111+ .filter((line) => line.length > 0)112+ .map((line) => JSON.parse(line) as Record<string, unknown>);113+}114+115+async function waitForFileContent(filePath: string, attempts = 40) {116+ for (let attempt = 0; attempt < attempts; attempt += 1) {117+ try {118+ const raw = await NodeFSP.readFile(filePath, "utf8");119+ if (raw.trim().length > 0) {120+ return raw;121+ }122+ } catch {}123+ // Microtask yield, matching the previous Effect.yieldNow pacing: each loop124+ // iteration already awaits real fs I/O, so no wall-clock timer is needed.125+ await Promise.resolve();126+ }127+ throw new Error(`Timed out waiting for file content at ${filePath}`);128+}apps/server/src/provider/Layers/OmpAdapter.test.ts lines 371 to 374OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +354,21 @@354+ const req = request([{ kind: "allow_once", optionId: "ok" }]);355+ expect(selectOmpPermissionOptionId(req, "decline")).toBeUndefined();356+ });357+});358+359+const ompAdapterTestLayer = it.layer(makeOmpAdapterTestLayer());360+361+ompAdapterTestLayer("OmpAdapterLive", (it) => {362+ it.effect("starts a session and maps mock ACP prompt flow to runtime events", () =>363+ Effect.gen(function* () {364+ const adapter = yield* OmpAdapter;365+ const settings = yield* ServerSettingsService;366+ const threadId = ThreadId.make("omp-mock-thread");367+368+ const wrapperPath = yield* Effect.promise(() => makeMockAgentWrapper());369+ yield* settings.updateSettings({ providers: { omp: { binaryPath: wrapperPath } } });370+371+ const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe(372+ Stream.runCollect,373+ Effect.forkChild,374+ );
juliusmarminge closed this
Sign in to join this conversation.


macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed