feat(server): add Oh My Pi (omp) as an ACP provider #9038
ClosedNeon-Wang(GitHub profile, opens in a new tab)wants to merge 10 commits into
main fromrefs/pull/9038/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
- apps/server/src/provider/Layers/OmpAdapter.test.ts line 3Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1 @@1+// @effect-diagnostics nodeBuiltinImport:off
- apps/server/src/provider/Layers/OmpAdapter.ts line 1199Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1105,21 @@1105+ provider: PROVIDER,1106+ threadId: input.threadId,1107+ payload: { providerThreadId: started.sessionId },1108+ });1109+1110+ return session;1111+ }).pipe(Effect.scoped),1112+ );1113+1114+ const sendTurn: OmpAdapterShape["sendTurn"] = (input) =>1115+ Effect.gen(function* () {1116+ const ctx = yield* requireSession(input.threadId);1117+ // A sendTurn while a prompt is in flight is a steer: the agent folds1118+ // the new prompt into the ongoing work, so the active turn id is1119+ // reused instead of opening a new turn.1120+ const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;1121+ const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);1122+ // Count this prompt immediately so a superseded in-flight prompt1123+ // resolving from here on does not settle the turn; the matching1124+ // decrement is the `ensuring` below.1125+ ctx.promptsInFlight += 1;@@ -0,0 +340,21 @@340+ segments.push(segment.charAt(0).toUpperCase() + segment.slice(1));341+ }342+ }343+ return segments.join(" ");344+}345+346+/**347+ * Oh My Pi is a meta provider (like OpenCode): model ids advertised through348+ * the ACP `model` config option are `provider/model` pairs routed to upstream349+ * providers the user configured inside omp. Mirror OpenCode's presentation350+ * by surfacing the upstream provider as `subProvider` and sorting the catalog351+ * by display name so the picker stays usable with 100+ entries.352+ */353+function buildOmpDiscoveredModelsFromConfigOptions(354+ configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,355+): ReadonlyArray<ServerProviderModel> {356+ const modelOption = findOmpModelConfigOption(configOptions ?? []);357+ if (!modelOption) {358+ return [];359+ }360+ const capabilities = buildOmpCapabilitiesFromConfigOptions(configOptions);apps/server/src/provider/Layers/OmpProvider.ts lines 148 to 150Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +127,21 @@127+ );128+}129+130+function normalizeOmpReasoningValue(value: string | null | undefined): string | undefined {131+ const normalized = value?.trim().toLowerCase();132+ switch (normalized) {133+ case "off":134+ case "none":135+ return "off";136+ case "low":137+ case "medium":138+ case "high":139+ case "max":140+ return normalized;141+ case "xhigh":142+ case "extra-high":143+ case "extra high":144+ return "xhigh";145+ default:146+ return undefined;147+ }apps/server/src/provider/Layers/OmpAdapter.ts line 535Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +455,21 @@455+ if (!task) {456+ return undefined;457+ }458+ const role = optionalTrimmedString(item.agent);459+ const effort = optionalTrimmedString(item.effort);460+ return {461+ taskId,462+ title: truncateTaskText(optionalTrimmedString(item.name) ?? task, OMP_TASK_TITLE_MAX_CHARS),463+ ...(role ? { role } : {}),464+ ...(effort ? { effort } : {}),465+ };466+}467+468+function parseOmpSubagentSpawns(469+ toolCallId: string,470+ rawInput: unknown,471+): ReadonlyArray<OmpSubagentSpawn> {472+ if (!isRecord(rawInput)) {473+ return [];474+ }475+ if (Array.isArray(rawInput.tasks)) {
- apps/web/src/components/settings/providerDriverMeta.ts line 84Resolvedby Neon-Wang(GitHub profile, opens in a new tab)@@ -67,3 +76,7 @@6776 icon: OpenCodeIcon,6877 settingsSchema: OpenCodeSettings,6978 },79+ {80+ value: ProviderDriverKind.make("omp"),81+ label: "Oh My Pi",82+ icon: PiAgentIcon,apps/web/src/components/chat/providerIconUtils.ts line 20Resolvedby Neon-Wang(GitHub profile, opens in a new tab)@@ -8,3 +8,4 @@88 [ProviderDriverKind.make("opencode")]: OpenCodeIcon,99 [ProviderDriverKind.make("cursor")]: CursorIcon,1010 [ProviderDriverKind.make("grok")]: GrokIcon,11+ [ProviderDriverKind.make("omp")]: PiAgentIcon,
- apps/server/src/textGeneration/OmpTextGeneration.ts line 77Resolvedby Neon-Wang(GitHub profile, opens in a new tab)@@ -0,0 +48,21 @@48+ modelSelection,49+ }: {50+ operation:51+ | "generateCommitMessage"52+ | "generatePrContent"53+ | "generateBranchName"54+ | "generateThreadTitle";55+ cwd: string;56+ prompt: string;57+ outputSchemaJson: S;58+ modelSelection: ModelSelection;59+ }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>60+ Effect.gen(function* () {61+ const outputRef = yield* Ref.make("");62+ const runtime = yield* makeOmpAcpRuntime({63+ ompSettings,64+ environment: resolvedEnvironment,65+ childProcessSpawner: commandSpawner,66+ cwd,67+ clientInfo: { name: "t3-code-git-text", version: "0.0.0" },68+ }).pipe(Effect.provideService(Crypto.Crypto, crypto));apps/server/src/provider/Layers/OmpAdapter.ts line 1372Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +1234,21 @@1234+ activeTurnId: turnId,1235+ updatedAt: yield* nowIso,1236+ ...(resolvedModel ? { model: resolvedModel } : {}),1237+ };1238+1239+ // Only the last remaining prompt settles the turn — a steer-1240+ // superseded prompt resolving (usually cancelled) while another is1241+ // in flight or pending must leave the merged turn running.1242+ if (ctx.promptsInFlight === 1) {1243+ yield* offerRuntimeEvent({1244+ type: "turn.completed",1245+ ...(yield* makeEventStamp()),1246+ provider: PROVIDER,1247+ threadId: input.threadId,1248+ turnId,1249+ payload: {1250+ state: result.stopReason === "cancelled" ? "cancelled" : "completed",1251+ stopReason: result.stopReason ?? null,1252+ },1253+ });1254+ }
- apps/server/src/provider/Layers/OmpAdapter.ts line 1233Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1141,21 @@1141+ const ctx = yield* requireSession(input.threadId);1142+ // A sendTurn while a prompt is in flight is a steer: the agent folds1143+ // the new prompt into the ongoing work, so the active turn id is1144+ // reused instead of opening a new turn.1145+ const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;1146+ const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);1147+ // Count this prompt immediately so a superseded in-flight prompt1148+ // resolving from here on does not settle the turn; the matching1149+ // decrement is the `ensuring` below. Bind the active turn id in the1150+ // same synchronous stretch: after the increment, a concurrent1151+ // sendTurn must already see this turn id or it would steer onto the1152+ // previous one.1153+ ctx.promptsInFlight += 1;1154+ ctx.activeTurnId = turnId;1155+1156+ return yield* Effect.gen(function* () {1157+ const turnModelSelection =1158+ input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;1159+ const model = turnModelSelection?.model ?? ctx.session.model;1160+ const resolvedModel = resolveOmpAcpBaseModelId(model);1161+ yield* applyRequestedSessionConfiguration({apps/server/src/provider/Layers/OmpAdapter.ts line 610Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +555,21 @@555+ detail: "Failed to generate Oh My Pi runtime identifier.",556+ cause,557+ }),558+ ),559+ );560+ const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));561+ const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });562+563+ const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>564+ PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);565+566+ const getThreadSemaphore = (threadId: string) =>567+ SynchronizedRef.modifyEffect(threadLocksRef, (current) => {568+ const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(569+ current.get(threadId),570+ );571+ return Option.match(existing, {572+ onNone: () =>573+ Semaphore.make(1).pipe(574+ Effect.map((semaphore) => {575+ const next = new Map(current);apps/server/src/provider/Layers/OmpAdapter.ts line 1265Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1165,21 @@1165+ modelSelection:1166+ model === undefined1167+ ? undefined1168+ : {1169+ model,1170+ options: turnModelSelection?.options,1171+ },1172+ mapError: ({ cause, method }) =>1173+ mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),1174+ });1175+ if (steeringTurnId === undefined) {1176+ ctx.lastPlanFingerprint = undefined;1177+ }1178+ ctx.session = {1179+ ...ctx.session,1180+ activeTurnId: turnId,1181+ updatedAt: yield* nowIso,1182+ };1183+1184+ if (steeringTurnId === undefined) {1185+ yield* offerRuntimeEvent({
- apps/server/src/textGeneration/OmpTextGeneration.ts line 71Resolvedby Neon-Wang(GitHub profile, opens in a new tab)@@ -0,0 +51,21 @@51+ | "generateCommitMessage"52+ | "generatePrContent"53+ | "generateBranchName"54+ | "generateThreadTitle";55+ cwd: string;56+ prompt: string;57+ outputSchemaJson: S;58+ modelSelection: ModelSelection;59+ }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>60+ Effect.gen(function* () {61+ const outputRef = yield* Ref.make("");62+ const runtime = yield* makeOmpAcpRuntime({63+ ompSettings,64+ environment: resolvedEnvironment,65+ childProcessSpawner: commandSpawner,66+ cwd,67+ // Background text generation is unattended: nobody can answer an68+ // approval prompt, and this path registers no permission/elicitation69+ // handlers. `--auto-approve` keeps omp's wrapper layer and permission70+ // gate from ever pausing the one-shot generation.71+ runtimeMode: "auto",
- apps/server/src/provider/Layers/OmpAdapter.test.ts line 1428Resolvedby Neon-Wang(GitHub profile, opens in a new tab)@@ -0,0 +1370,21 @@1370+ yield* adapter.stopSession(threadId);1371+ }),1372+ );1373+1374+ it.effect("cancelling during sendTurn preparation prevents the prompt from being sent", () =>1375+ Effect.gen(function* () {1376+ const adapter = yield* OmpAdapter;1377+ const serverSettings = yield* ServerSettingsService;1378+ const threadId = ThreadId.make("omp-prepare-cancel");1379+ const tempDir = yield* Effect.promise(() =>1380+ NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "omp-acp-")),1381+ );1382+ const requestLogPath = NodePath.join(tempDir, "requests.ndjson");1383+ const argvLogPath = NodePath.join(tempDir, "argv.txt");1384+ yield* Effect.promise(() => NodeFSP.writeFile(requestLogPath, "", "utf8"));1385+ // Slow set_config_option responses keep the prepare phase busy long1386+ // enough for interruptTurn to land before the prompt goes out.1387+ const wrapperPath = yield* Effect.promise(() =>1388+ makeProbeWrapper(requestLogPath, argvLogPath, {1389+ T3_ACP_SET_CONFIG_OPTION_DELAY_MS: "500",1390+ }),apps/server/src/provider/Layers/OmpAdapter.ts line 1411Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +1367,21 @@1367+ const message =1368+ typeof error === "object" && error !== null && "message" in error1369+ ? error.message1370+ : undefined;1371+ yield* offerRuntimeEvent({1372+ type: "turn.completed",1373+ ...(yield* makeEventStamp()),1374+ provider: PROVIDER,1375+ threadId: input.threadId,1376+ turnId,1377+ payload: {1378+ state: "failed",1379+ stopReason: null,1380+ errorMessage: truncateTaskText(1381+ typeof message === "string" ? message : String(error),1382+ OMP_TURN_ERROR_MAX_CHARS,1383+ ),1384+ },1385+ });1386+ }),1387+ ),
- apps/server/src/provider/Layers/OmpAdapter.ts line 1399OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1379,21 @@1379+ turnId,1380+ payload: {1381+ state: "failed",1382+ stopReason: null,1383+ errorMessage: truncateTaskText(1384+ typeof message === "string" ? message : String(error),1385+ OMP_TURN_ERROR_MAX_CHARS,1386+ ),1387+ },1388+ });1389+ }),1390+ ),1391+ Effect.ensuring(1392+ Effect.sync(() => {1393+ ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);1394+ }),1395+ ),1396+ );1397+ });1398+1399+ const interruptTurn: OmpAdapterShape["interruptTurn"] = (threadId) =>
- apps/server/src/provider/Layers/OmpAdapter.ts line 961OutdatedResolvedby Neon-Wang(GitHub profile, opens in a new tab)@@ -0,0 +941,21 @@941+ );942+ const resolved = yield* Deferred.await(decision);943+ pendingApprovals.delete(requestId);944+ yield* offerRuntimeEvent(945+ makeAcpRequestResolvedEvent({946+ stamp: yield* makeEventStamp(),947+ provider: PROVIDER,948+ threadId: input.threadId,949+ turnId: ctx?.activeTurnId,950+ requestId: runtimeRequestId,951+ permissionRequest,952+ decision: resolved,953+ }),954+ );955+ return {956+ outcome:957+ resolved === "cancel"958+ ? ({ outcome: "cancelled" } as const)959+ : {960+ outcome: "selected" as const,961+ optionId: acpPermissionOutcome(resolved),
- apps/server/src/provider/Layers/OmpAdapter.ts line 1433Resolvedby Neon-Wang(GitHub profile, opens in a new tab)@@ -0,0 +1380,21 @@1380+ Effect.gen(function* () {1381+ ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);1382+ // The last prompt of a turn cancelled during preparation1383+ // settles it here: the checkpoints kept the mark because other1384+ // prompts were still in flight.1385+ if (ctx.promptsInFlight === 0 && ctx.cancelledTurnIds.has(turnId)) {1386+ // Finalizers cannot fail; a crypto failure here must not1387+ // mask the sendTurn outcome.1388+ yield* Effect.ignore(1389+ Effect.gen(function* () {1390+ ctx.cancelledTurnIds.delete(turnId);1391+ yield* offerRuntimeEvent({1392+ type: "turn.completed",1393+ ...(yield* makeEventStamp()),1394+ provider: PROVIDER,1395+ threadId: input.threadId,1396+ turnId,1397+ payload: { state: "cancelled", stopReason: "cancelled" },1398+ });1399+ }),1400+ );
- @@ -0,0 +1331,21 @@1331+ }1332+1333+ const result = yield* ctx.acp1334+ .prompt({1335+ prompt: promptParts,1336+ })1337+ .pipe(1338+ Effect.mapError((error) =>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,@@ -0,0 +1053,21 @@1053+ session,1054+ scope: sessionScope,1055+ acp,1056+ notificationFiber: undefined,1057+ pendingApprovals,1058+ pendingUserInputs,1059+ cancelledTurnIds: new Set(),1060+ ompSubagentTasks: new Map(),1061+ turns: [],1062+ lastPlanFingerprint: undefined,1063+ activeTurnId: undefined,1064+ promptsInFlight: 0,1065+ stopped: false,1066+ };1067+1068+ const nf = yield* Stream.runDrain(1069+ Stream.mapEffect(acp.getEvents(), (event) =>1070+ Effect.gen(function* () {1071+ switch (event._tag) {1072+ case "EventStreamBarrier":1073+ yield* Deferred.succeed(event.acknowledge, undefined);
- apps/web/src/session-logic.ts lines 65 to 71Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -61,5 +61,11 @@6161 available: true,6262 pickerSidebarBadge: "new",6363 },64+ {65+ value: ProviderDriverKind.make("omp"),66+ label: "Oh My Pi",67+ available: true,68+ pickerSidebarBadge: "new",69+ },6470 {6571 value: ProviderDriverKind.make("antigravity"),@@ -0,0 +699,21 @@699+ });700+ discoveryWarning = OMP_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;701+ } else if (Option.isNone(discoveryExit.value)) {702+ discoveryWarning = `Oh My Pi ACP model discovery timed out after ${OMP_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;703+ } else if (discoveryExit.value.value.length === 0) {704+ discoveryWarning = "Oh My Pi ACP model discovery returned no built-in models.";705+ } else {706+ discoveredModels = discoveryExit.value;707+ }708+ const resolvedModels = Option.getOrElse(709+ Option.filter(discoveredModels, (models) => models.length > 0),710+ () => [] as const,711+ );712+ // Meta-provider reporting (mirrors OpenCode): tell the user how many713+ // upstream providers the discovered `provider/model` catalog routes to.714+ const upstreamCount = countOmpUpstreamProviders(resolvedModels);715+ return buildOmpProviderSnapshot({716+ checkedAt,717+ ompSettings,718+ version,719+ discoveredModels: resolvedModels,
- @@ -0,0 +440,21 @@440+ ? false441+ : undefined;442+ if (value !== undefined) {443+ content[key] = value;444+ }445+ continue;446+ }447+ if (property.type === "array") {448+ const values = Array.isArray(raw)449+ ? raw.filter(450+ (value): value is string => typeof value === "string" && value.trim().length > 0,451+ )452+ : typeof raw === "string" && raw.trim().length > 0453+ ? [raw]454+ : [];455+ if (values.length > 0) {456+ content[key] = values;457+ }458+ continue;459+ }460+ if (typeof raw === "string" && raw.trim().length > 0) {@@ -0,0 +373,21 @@373+ readonly sessionId?: string | undefined;374+ readonly message?: string | undefined;375+ readonly requestedSchema?:376+ | {377+ readonly type?: string | undefined;378+ readonly properties?: Readonly<Record<string, OmpElicitationPropertyLike>> | undefined;379+ }380+ | undefined;381+}382+383+/**384+ * Maps an omp form elicitation's JSON-schema properties onto T3 user-input385+ * questions. Select-style properties (string+enum, boolean) get option lists;386+ * everything else falls back to free text (the web composer supports custom387+ * answers).388+ */389+export function ompElicitationQuestionsFromForm(390+ params: OmpElicitationFormLike,391+): ReadonlyArray<UserInputQuestion> {392+ const fallbackQuestion = params.message?.trim() || "Oh My Pi requests input.";393+ return Object.entries(params.requestedSchema?.properties ?? {}).map(([key, property]) => {
- @@ -0,0 +1180,21 @@1180+1181+ return session;1182+ }).pipe(Effect.scoped),1183+ );1184+1185+ const sendTurn: OmpAdapterShape["sendTurn"] = (input) =>1186+ Effect.gen(function* () {1187+ const ctx = yield* requireSession(input.threadId);1188+ // A sendTurn while a prompt is in flight is a steer: the agent folds1189+ // the new prompt into the ongoing work, so the active turn id is1190+ // reused instead of opening a new turn.1191+ const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;1192+ const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);1193+ // Count this prompt immediately so a superseded in-flight prompt1194+ // resolving from here on does not settle the turn; the matching1195+ // decrement is the `ensuring` below. Bind the active turn id in the1196+ // same synchronous stretch: after the increment, a concurrent1197+ // sendTurn must already see this turn id or it would steer onto the1198+ // previous one.1199+ ctx.promptsInFlight += 1;1200+ ctx.activeTurnId = turnId;
juliusmarminge closed this
Sign in to join this conversation.






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