Open History to see the last commit
1import type {
2 OmpSettings,
3 ModelCapabilities,
4 ProviderOptionSelection,
5 ServerProvider,
6 ServerProviderModel,
7 ServerProviderState,
8} from "@t3tools/contracts";
9import type * as EffectAcpSchema from "effect-acp/schema";
10import { causeErrorTag } from "@t3tools/shared/observability";
11import * as Crypto from "effect/Crypto";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as Exit from "effect/Exit";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Result from "effect/Result";
18import { HttpClient } from "effect/unstable/http";
19import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
20import {
21 createModelCapabilities,
22 getProviderOptionBooleanSelectionValue,
23 getProviderOptionStringSelectionValue,
24} from "@t3tools/shared/model";
25import { resolveSpawnCommand } from "@t3tools/shared/shell";
26
27import {
28 buildBooleanOptionDescriptor,
29 buildSelectOptionDescriptor,
30 buildServerProvider,
31 isCommandMissingCause,
32 parseGenericCliVersion,
33 providerModelsFromSettings,
34 spawnAndCollect,
35 type ServerProviderDraft,
36} from "../providerSnapshot.ts";
37import {
38 enrichProviderSnapshotWithVersionAdvisory,
39 type ProviderMaintenanceCapabilities,
40} from "../providerMaintenance.ts";
41import * as AcpSessionRuntime from "../acp/AcpSessionRuntime.ts";
42
43const OMP_PRESENTATION = {
44 displayName: "Oh My Pi",
45 badgeLabel: "Early Access",
46 showInteractionModeToggle: true,
47} as const;
48const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
49 optionDescriptors: [],
50});
51
52const VERSION_PROBE_TIMEOUT_MS = 4_000;
53const OMP_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
54const OMP_CLI_DOCS_URL = "https://github.com/can1357/oh-my-pi";
55const OMP_ACP_MODEL_DISCOVERY_FAILED_MESSAGE = [
56 "Oh My Pi ACP model discovery failed.",
57 "The omp CLI setup may be incomplete; install or enable the omp CLI, restart T3 Code, and try again.",
58 `See ${OMP_CLI_DOCS_URL}.`,
59 "Check server logs for ACP details.",
60].join(" ");
61
62export function buildInitialOmpProviderSnapshot(
63 ompSettings: OmpSettings,
64): Effect.Effect<ServerProviderDraft> {
65 return Effect.gen(function* () {
66 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
67 const models = getOmpFallbackModels(ompSettings);
68
69 if (!ompSettings.enabled) {
70 return buildServerProvider({
71 presentation: OMP_PRESENTATION,
72 enabled: false,
73 checkedAt,
74 models,
75 probe: {
76 installed: false,
77 version: null,
78 status: "warning",
79 auth: { status: "unknown" },
80 message: "Oh My Pi is disabled in T3 Code settings.",
81 },
82 });
83 }
84
85 return buildServerProvider({
86 presentation: OMP_PRESENTATION,
87 enabled: true,
88 checkedAt,
89 models,
90 probe: {
91 installed: true,
92 version: null,
93 status: "warning",
94 auth: { status: "unknown" },
95 message: "Checking Oh My Pi availability...",
96 },
97 });
98 });
99}
100
101interface OmpSessionSelectOption {
102 readonly value: string;
103 readonly name: string;
104}
105
106export function flattenSessionConfigSelectOptions(
107 configOption: EffectAcpSchema.SessionConfigOption | undefined,
108): ReadonlyArray<OmpSessionSelectOption> {
109 if (!configOption || configOption.type !== "select") {
110 return [];
111 }
112 return configOption.options.flatMap((entry) =>
113 "value" in entry
114 ? [
115 {
116 value: entry.value.trim(),
117 name: entry.name.trim(),
118 } satisfies OmpSessionSelectOption,
119 ]
120 : entry.options.map(
121 (option) =>
122 ({
123 value: option.value.trim(),
124 name: option.name.trim(),
125 }) satisfies OmpSessionSelectOption,
126 ),
127 );
128}
129
130function 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 // omp's thinking select legitimately offers {off, auto} on auto models.
137 case "auto":
138 return "auto";
139 case "low":
140 case "medium":
141 case "high":
142 case "max":
143 return normalized;
144 case "xhigh":
145 case "extra-high":
146 case "extra high":
147 return "xhigh";
148 default:
149 return undefined;
150 }
151}
152
153function getOmpConfigOptionCategory(option: EffectAcpSchema.SessionConfigOption): string {
154 return option.category?.trim().toLowerCase() ?? "";
155}
156
157function isOmpEffortConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean {
158 if (getOmpConfigOptionCategory(option) === "thought_level") {
159 return true;
160 }
161 const id = option.id.trim().toLowerCase();
162 const name = option.name.trim().toLowerCase();
163 return (
164 id === "effort" ||
165 id === "reasoning" ||
166 id === "thinking" ||
167 name === "effort" ||
168 name === "reasoning" ||
169 name.includes("effort") ||
170 name.includes("reasoning")
171 );
172}
173
174function findOmpEffortConfigOption(
175 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
176): EffectAcpSchema.SessionConfigOption | undefined {
177 const candidates = configOptions.filter(
178 (option) => option.type === "select" && isOmpEffortConfigOption(option),
179 );
180 return (
181 candidates.find((option) => getOmpConfigOptionCategory(option) === "thought_level") ??
182 candidates.find((option) => option.id.trim().toLowerCase() === "effort") ??
183 candidates.find((option) => getOmpConfigOptionCategory(option) === "model_option") ??
184 candidates[0]
185 );
186}
187
188function isOmpContextConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean {
189 const id = option.id.trim().toLowerCase();
190 const name = option.name.trim().toLowerCase();
191 return id === "context" || id === "context_size" || name.includes("context");
192}
193
194function isOmpFastConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean {
195 const id = option.id.trim().toLowerCase();
196 const name = option.name.trim().toLowerCase();
197 return id === "fast" || name === "fast" || name.includes("fast mode");
198}
199
200function isBooleanLikeConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean {
201 if (option.type === "boolean") {
202 return true;
203 }
204 if (option.type !== "select") {
205 return false;
206 }
207 const values = new Set(
208 flattenSessionConfigSelectOptions(option).map((entry) => entry.value.trim().toLowerCase()),
209 );
210 return values.has("true") && values.has("false");
211}
212
213function getBooleanCurrentValue(
214 option: EffectAcpSchema.SessionConfigOption | undefined,
215): boolean | undefined {
216 if (!option) {
217 return undefined;
218 }
219 if (option.type === "boolean") {
220 return option.currentValue;
221 }
222 if (option.type !== "select") {
223 return undefined;
224 }
225 const normalized = option.currentValue?.trim().toLowerCase();
226 if (normalized === "true") {
227 return true;
228 }
229 if (normalized === "false") {
230 return false;
231 }
232 return undefined;
233}
234
235export function buildOmpCapabilitiesFromConfigOptions(
236 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
237): ModelCapabilities {
238 if (!configOptions || configOptions.length === 0) {
239 return EMPTY_CAPABILITIES;
240 }
241
242 const reasoningConfig = findOmpEffortConfigOption(configOptions);
243 const reasoningEffortLevels =
244 reasoningConfig?.type === "select"
245 ? flattenSessionConfigSelectOptions(reasoningConfig).flatMap((entry) => {
246 const normalizedValue = normalizeOmpReasoningValue(entry.value);
247 if (!normalizedValue) {
248 return [];
249 }
250 return [
251 {
252 value: normalizedValue,
253 label: entry.name,
254 ...(normalizeOmpReasoningValue(reasoningConfig.currentValue) === normalizedValue
255 ? { isDefault: true }
256 : {}),
257 },
258 ];
259 })
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?.trim() === 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 : [];
281
282 const fastOption = configOptions.find(
283 (option) => option.category === "model_config" && isOmpFastConfigOption(option),
284 );
285 const fastCurrentValue = getBooleanCurrentValue(fastOption);
286 const optionDescriptors = [
287 ...(reasoningEffortLevels.length > 0
288 ? [
289 buildSelectOptionDescriptor({
290 id: "reasoning",
291 label: reasoningConfig?.name?.trim() || "Reasoning",
292 options: reasoningEffortLevels,
293 }),
294 ]
295 : []),
296 ...(contextWindowOptions.length > 0
297 ? [
298 buildSelectOptionDescriptor({
299 id: "contextWindow",
300 label: contextOption?.name?.trim() || "Context Window",
301 options: contextWindowOptions,
302 }),
303 ]
304 : []),
305 ...(fastOption && isBooleanLikeConfigOption(fastOption)
306 ? [
307 typeof fastCurrentValue === "boolean"
308 ? buildBooleanOptionDescriptor({
309 id: "fastMode",
310 label: fastOption.name?.trim() || "Fast Mode",
311 currentValue: fastCurrentValue,
312 })
313 : buildBooleanOptionDescriptor({
314 id: "fastMode",
315 label: fastOption.name?.trim() || "Fast Mode",
316 }),
317 ]
318 : []),
319 ];
320
321 return createModelCapabilities({
322 optionDescriptors,
323 });
324}
325
326/**
327 * Existence probe without the select guard: ACP permits a boolean option
328 * named `model`, and callers that write model values must distinguish
329 * "no model option at all" from "a model option that cannot accept a slug".
330 */
331export function findOmpModelConfigOptionAny(
332 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
333): EffectAcpSchema.SessionConfigOption | undefined {
334 return (
335 configOptions.find((option) => getOmpConfigOptionCategory(option) === "model") ??
336 configOptions.find((option) => option.id.trim().toLowerCase() === "model")
337 );
338}
339
340export function findOmpModelConfigOption(
341 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
342): EffectAcpSchema.SessionConfigOption | undefined {
343 return (
344 configOptions.find(
345 (option) => option.type === "select" && getOmpConfigOptionCategory(option) === "model",
346 ) ??
347 configOptions.find(
348 (option) => option.type === "select" && option.id.trim().toLowerCase() === "model",
349 )
350 );
351}
352
353function titleCaseSlug(value: string): string {
354 const segments: Array<string> = [];
355 for (const segment of value.split(/[-_/]+/)) {
356 if (segment.length > 0) {
357 segments.push(segment.charAt(0).toUpperCase() + segment.slice(1));
358 }
359 }
360 return segments.join(" ");
361}
362
363/**
364 * Oh My Pi is a meta provider (like OpenCode): model ids advertised through
365 * the ACP `model` config option are `provider/model` pairs routed to upstream
366 * providers the user configured inside omp. Mirror OpenCode's presentation
367 * by surfacing the upstream provider as `subProvider` and sorting the catalog
368 * by display name so the picker stays usable with 100+ entries.
369 */
370function buildOmpDiscoveredModelsFromConfigOptions(
371 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
372): ReadonlyArray<ServerProviderModel> {
373 const modelOption = findOmpModelConfigOption(configOptions ?? []);
374 if (!modelOption) {
375 return [];
376 }
377 // The probe session's configOptions describe the model it currently has
378 // selected (omp re-validates dependent options per model). Advertising
379 // those capabilities for every catalog entry would offer invalid
380 // reasoning choices on other models, so only the probed model carries
381 // them; the rest report null and the adapter re-reads options per model
382 // at selection time.
383 const currentModelId =
384 modelOption.type === "select" ? modelOption.currentValue?.trim() : undefined;
385 const probedCapabilities = buildOmpCapabilitiesFromConfigOptions(configOptions);
386 const seen = new Set<string>();
387 const models = flattenSessionConfigSelectOptions(modelOption).flatMap((entry) => {
388 if (!entry.value || seen.has(entry.value)) {
389 return [];
390 }
391 seen.add(entry.value);
392 const slashIndex = entry.value.indexOf("/");
393 const subProvider =
394 slashIndex > 0 ? titleCaseSlug(entry.value.slice(0, slashIndex)) : undefined;
395 return [
396 {
397 slug: entry.value,
398 name: entry.name || entry.value,
399 ...(subProvider ? { subProvider } : {}),
400 isCustom: false,
401 capabilities: entry.value === currentModelId ? probedCapabilities : null,
402 } satisfies ServerProviderModel,
403 ];
404 });
405 return models.toSorted((left, right) => left.name.localeCompare(right.name));
406}
407
408function countOmpUpstreamProviders(models: ReadonlyArray<ServerProviderModel>): number {
409 const prefixes = new Set<string>();
410 for (const model of models) {
411 const slashIndex = model.slug.indexOf("/");
412 if (slashIndex > 0) {
413 prefixes.add(model.slug.slice(0, slashIndex));
414 }
415 }
416 return prefixes.size;
417}
418
419const makeOmpAcpProbeRuntime = (ompSettings: OmpSettings, environment?: NodeJS.ProcessEnv) =>
420 Effect.gen(function* () {
421 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
422 const acpContext = yield* Layer.build(
423 AcpSessionRuntime.layer({
424 spawn: {
425 command: ompSettings.binaryPath || "omp",
426 args: ["acp"],
427 cwd: process.cwd(),
428 ...(environment ? { env: environment } : {}),
429 },
430 cwd: process.cwd(),
431 clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
432 authMethodId: "agent",
433 }).pipe(Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner))),
434 );
435 return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
436 Effect.provide(acpContext),
437 );
438 });
439
440export const discoverOmpModelsViaAcp = (
441 ompSettings: OmpSettings,
442 environment?: NodeJS.ProcessEnv,
443) =>
444 makeOmpAcpProbeRuntime(ompSettings, environment).pipe(
445 Effect.flatMap((acp) =>
446 Effect.map(acp.start(), (started) =>
447 buildOmpDiscoveredModelsFromConfigOptions(started.sessionSetupResult.configOptions),
448 ),
449 ),
450 Effect.scoped,
451 );
452
453export function getOmpFallbackModels(
454 ompSettings: Pick<OmpSettings, "customModels">,
455): ReadonlyArray<ServerProviderModel> {
456 return providerModelsFromSettings([], ompSettings.customModels, EMPTY_CAPABILITIES);
457}
458
459function normalizeOmpConfigOptionToken(value: string | null | undefined): string {
460 return (
461 value
462 ?.trim()
463 .toLowerCase()
464 .replace(/[\s_-]+/g, "-") ?? ""
465 );
466}
467
468function findOmpSelectOptionValue(
469 configOption: EffectAcpSchema.SessionConfigOption | undefined,
470 matcher: (option: OmpSessionSelectOption) => boolean,
471): string | undefined {
472 return flattenSessionConfigSelectOptions(configOption).find(matcher)?.value;
473}
474
475function findOmpBooleanConfigValue(
476 configOption: EffectAcpSchema.SessionConfigOption | undefined,
477 requested: boolean,
478): string | boolean | undefined {
479 if (!configOption) {
480 return undefined;
481 }
482 if (configOption.type === "boolean") {
483 return requested;
484 }
485 return findOmpSelectOptionValue(
486 configOption,
487 (option) => normalizeOmpConfigOptionToken(option.value) === String(requested),
488 );
489}
490
491export function resolveOmpAcpConfigUpdates(
492 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
493 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
494): ReadonlyArray<{
495 readonly configId: string;
496 readonly value: string | boolean;
497}> {
498 if (!configOptions || configOptions.length === 0) {
499 return [];
500 }
501
502 const updates: Array<{
503 readonly configId: string;
504 readonly value: string | boolean;
505 }> = [];
506
507 const reasoningOption = findOmpEffortConfigOption(configOptions);
508 const requestedReasoning = normalizeOmpReasoningValue(
509 getProviderOptionStringSelectionValue(selections, "reasoning"),
510 );
511 if (reasoningOption && requestedReasoning) {
512 const value = findOmpSelectOptionValue(reasoningOption, (option) => {
513 const normalizedValue = normalizeOmpReasoningValue(option.value);
514 const normalizedName = normalizeOmpReasoningValue(option.name);
515 return normalizedValue === requestedReasoning || normalizedName === requestedReasoning;
516 });
517 if (value) {
518 updates.push({ configId: reasoningOption.id, value });
519 }
520 }
521
522 const contextOption = configOptions.find(
523 (option) => option.category === "model_config" && isOmpContextConfigOption(option),
524 );
525 const requestedContextWindow = getProviderOptionStringSelectionValue(selections, "contextWindow");
526 if (contextOption && requestedContextWindow) {
527 const value = findOmpSelectOptionValue(
528 contextOption,
529 (option) =>
530 normalizeOmpConfigOptionToken(option.value) ===
531 normalizeOmpConfigOptionToken(requestedContextWindow) ||
532 normalizeOmpConfigOptionToken(option.name) ===
533 normalizeOmpConfigOptionToken(requestedContextWindow),
534 );
535 if (value) {
536 updates.push({ configId: contextOption.id, value });
537 }
538 }
539
540 const fastOption = configOptions.find(
541 (option) => option.category === "model_config" && isOmpFastConfigOption(option),
542 );
543 const requestedFastMode = getProviderOptionBooleanSelectionValue(selections, "fastMode");
544 if (fastOption && typeof requestedFastMode === "boolean") {
545 const value = findOmpBooleanConfigValue(fastOption, requestedFastMode);
546 if (value !== undefined) {
547 updates.push({ configId: fastOption.id, value });
548 }
549 }
550
551 return updates;
552}
553
554function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): string | undefined {
555 const parts: Array<string> = [];
556 for (const message of messages) {
557 const trimmed = message?.trim();
558 if (trimmed) {
559 parts.push(trimmed);
560 }
561 }
562 return parts.length > 0 ? parts.join(" ") : undefined;
563}
564
565function buildOmpCliCommandMissingMessage(binaryPath: string): string {
566 return [
567 `Oh My Pi CLI command \`${binaryPath}\` was not found.`,
568 `Install or enable the omp CLI, make sure \`${binaryPath}\` is on PATH, then restart T3 Code.`,
569 `See ${OMP_CLI_DOCS_URL}.`,
570 ].join(" ");
571}
572
573export function buildOmpProviderSnapshot(input: {
574 readonly checkedAt: string;
575 readonly ompSettings: OmpSettings;
576 readonly version: string | null;
577 readonly status?: Exclude<ServerProviderState, "disabled">;
578 readonly message?: string;
579 readonly discoveredModels?: ReadonlyArray<ServerProviderModel>;
580 readonly discoveryWarning?: string;
581}): ServerProviderDraft {
582 const status = input.status ?? "ready";
583 const message = joinProviderMessages(input.message, input.discoveryWarning);
584 return buildServerProvider({
585 presentation: OMP_PRESENTATION,
586 enabled: input.ompSettings.enabled,
587 checkedAt: input.checkedAt,
588 models: providerModelsFromSettings(
589 input.discoveredModels ?? [],
590 input.ompSettings.customModels,
591 EMPTY_CAPABILITIES,
592 ),
593 probe: {
594 installed: true,
595 version: input.version,
596 status: input.discoveryWarning && status === "ready" ? "warning" : status,
597 auth: { status: "unknown" },
598 ...(message ? { message } : {}),
599 },
600 });
601}
602
603const runOmpVersionCommand = (ompSettings: OmpSettings, environment?: NodeJS.ProcessEnv) =>
604 Effect.gen(function* () {
605 const command = ompSettings.binaryPath || "omp";
606 const spawnCommand = yield* resolveSpawnCommand(
607 command,
608 ["--version"],
609 environment ? { env: environment } : {},
610 );
611 return yield* spawnAndCollect(
612 command,
613 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
614 ...(environment ? { env: environment } : { extendEnv: true }),
615 shell: spawnCommand.shell,
616 }),
617 );
618 });
619
620export const checkOmpProviderStatus = Effect.fn("checkOmpProviderStatus")(function* (
621 ompSettings: OmpSettings,
622 environment?: NodeJS.ProcessEnv,
623): Effect.fn.Return<
624 ServerProviderDraft,
625 never,
626 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
627> {
628 const checkedAt = DateTime.formatIso(yield* DateTime.now);
629 const fallbackModels = getOmpFallbackModels(ompSettings);
630
631 if (!ompSettings.enabled) {
632 return buildServerProvider({
633 presentation: OMP_PRESENTATION,
634 enabled: false,
635 checkedAt,
636 models: fallbackModels,
637 probe: {
638 installed: false,
639 version: null,
640 status: "warning",
641 auth: { status: "unknown" },
642 message: "Oh My Pi is disabled in T3 Code settings.",
643 },
644 });
645 }
646
647 const versionProbe = yield* runOmpVersionCommand(ompSettings, environment).pipe(
648 Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),
649 Effect.result,
650 );
651
652 if (Result.isFailure(versionProbe)) {
653 const error = versionProbe.failure;
654 yield* Effect.logWarning("Oh My Pi CLI health check failed.", {
655 errorTag: error._tag,
656 });
657 return buildServerProvider({
658 presentation: OMP_PRESENTATION,
659 enabled: ompSettings.enabled,
660 checkedAt,
661 models: fallbackModels,
662 probe: {
663 installed: !isCommandMissingCause(error),
664 version: null,
665 status: "error",
666 auth: { status: "unknown" },
667 message: isCommandMissingCause(error)
668 ? buildOmpCliCommandMissingMessage(ompSettings.binaryPath || "omp")
669 : "Failed to execute Oh My Pi CLI health check.",
670 },
671 });
672 }
673
674 if (Option.isNone(versionProbe.success)) {
675 return buildServerProvider({
676 presentation: OMP_PRESENTATION,
677 enabled: ompSettings.enabled,
678 checkedAt,
679 models: fallbackModels,
680 probe: {
681 installed: true,
682 version: null,
683 status: "error",
684 auth: { status: "unknown" },
685 message: "Oh My Pi CLI is installed but timed out while running `omp --version`.",
686 },
687 });
688 }
689
690 const versionOutput = versionProbe.success.value;
691 const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
692 if (versionOutput.code !== 0) {
693 yield* Effect.logWarning("Oh My Pi CLI version probe exited with a non-zero status.", {
694 exitCode: versionOutput.code,
695 stdoutLength: versionOutput.stdout.length,
696 stderrLength: versionOutput.stderr.length,
697 });
698 return buildServerProvider({
699 presentation: OMP_PRESENTATION,
700 enabled: ompSettings.enabled,
701 checkedAt,
702 models: fallbackModels,
703 probe: {
704 installed: true,
705 version,
706 status: "error",
707 auth: { status: "unknown" },
708 message: "Oh My Pi CLI is installed but failed to run.",
709 },
710 });
711 }
712
713 let discoveredModels = Option.none<ReadonlyArray<ServerProviderModel>>();
714 let discoveryWarning: string | undefined;
715 const discoveryExit = yield* Effect.exit(
716 discoverOmpModelsViaAcp(ompSettings, environment).pipe(
717 Effect.timeoutOption(OMP_ACP_MODEL_DISCOVERY_TIMEOUT_MS),
718 ),
719 );
720 if (Exit.isFailure(discoveryExit)) {
721 yield* Effect.logWarning("Oh My Pi ACP model discovery failed", {
722 errorTag: causeErrorTag(discoveryExit.cause),
723 });
724 discoveryWarning = OMP_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;
725 } else if (Option.isNone(discoveryExit.value)) {
726 discoveryWarning = `Oh My Pi ACP model discovery timed out after ${OMP_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
727 } else if (discoveryExit.value.value.length === 0) {
728 discoveryWarning = "Oh My Pi ACP model discovery returned no built-in models.";
729 } else {
730 discoveredModels = discoveryExit.value;
731 }
732 const resolvedModels = Option.getOrElse(
733 Option.filter(discoveredModels, (models) => models.length > 0),
734 () => [] as const,
735 );
736 // Meta-provider reporting (mirrors OpenCode): tell the user how many
737 // upstream providers the discovered `provider/model` catalog routes to.
738 const upstreamCount = countOmpUpstreamProviders(resolvedModels);
739 return buildOmpProviderSnapshot({
740 checkedAt,
741 ompSettings,
742 version,
743 discoveredModels: resolvedModels,
744 ...(upstreamCount > 0
745 ? {
746 message: `${upstreamCount} upstream provider${upstreamCount === 1 ? "" : "s"} configured through Oh My Pi.`,
747 }
748 : {}),
749 ...(discoveryWarning ? { discoveryWarning } : {}),
750 });
751});
752
753/**
754 * Background maintenance enrichment for an Oh My Pi snapshot.
755 *
756 * Used by `OmpDriver` as the `makeManagedServerProvider.enrichSnapshot`
757 * hook: republishes update/version advisory metadata without performing any
758 * model or capability discovery. Oh My Pi model data comes exclusively from
759 * the probe ACP session during provider status checks.
760 */
761export const enrichOmpSnapshot = (input: {
762 readonly settings: OmpSettings;
763 readonly snapshot: ServerProvider;
764 readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
765 readonly enableProviderUpdateChecks?: boolean;
766 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
767 readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider;
768 readonly httpClient: HttpClient.HttpClient;
769}): Effect.Effect<void> => {
770 const { settings, snapshot, publishSnapshot } = input;
771 const stampIdentity = input.stampIdentity ?? ((value) => value);
772
773 if (!settings.enabled || snapshot.auth.status === "unauthenticated") {
774 return Effect.void;
775 }
776
777 return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
778 enableProviderUpdateChecks: input.enableProviderUpdateChecks,
779 }).pipe(
780 Effect.provideService(HttpClient.HttpClient, input.httpClient),
781 Effect.flatMap((enrichedSnapshot) =>
782 publishSnapshot(stampIdentity(enrichedSnapshot)).pipe(Effect.as(enrichedSnapshot)),
783 ),
784 Effect.catchCause((cause) =>
785 Effect.logWarning("Oh My Pi version advisory enrichment failed", {
786 errorTag: causeErrorTag(cause),
787 }).pipe(Effect.asVoid),
788 ),
789 );
790};