ollama-state.ts
2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* In-memory mirror of whether the engine is currently pointed at a local
* Ollama model, plus the exact model config that the next generation job
* should use. The server owns this (not coderio's dist) so that connecting/
* disconnecting takes effect for child-process generation without requiring a
* coderio rebuild — `loadServerModelConfig()` reads it below.
*/
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
import { resolve } from 'node:path';
import { homedir } from 'node:os';
const PERSIST_FILE = resolve(homedir(), '.coderio', 'ollama-active.json');
export interface OllamaRuntimeConfig {
provider: string;
model: string;
baseUrl: string;
apiKey: string;
}
let connected = false;
let activeModel: string | null = null;
let activeConfig: OllamaRuntimeConfig | null = null;
export function setOllamaConnected(model: string | null): void {
connected = model !== null;
activeModel = model;
}
export function getOllamaState(): { connected: boolean; activeModel: string | null } {
return { connected, activeModel };
}
/** Record the model config the engine should use while connected to Ollama. */
export function setOllamaConfig(cfg: OllamaRuntimeConfig | null): void {
activeConfig = cfg;
}
/** The Ollama config to inject into the next generation job, or null. */
export function getOllamaConfig(): OllamaRuntimeConfig | null {
return activeConfig;
}
/** Persist the active Ollama connection so it survives a server restart. */
export function persistOllama(cfg: OllamaRuntimeConfig): void {
try {
const dir = resolve(homedir(), '.coderio');
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
writeFileSync(PERSIST_FILE, JSON.stringify(cfg), 'utf8');
} catch {
/* best-effort: ignore persistence failures */
}
}
/** Clear the persisted connection (on disconnect). */
export function clearPersistedOllama(): void {
try {
if (existsSync(PERSIST_FILE)) writeFileSync(PERSIST_FILE, 'null', 'utf8');
} catch {
/* ignore */
}
}
/**
* Load a previously persisted connection. Returns null when none was saved.
* The stored `baseUrl` keeps the `/v1` suffix (OpenAI-compatible endpoint);
* callers that need the Ollama root (for health/model checks) strip it.
*/
export function loadPersistedOllama(): OllamaRuntimeConfig | null {
try {
if (!existsSync(PERSIST_FILE)) return null;
const raw = JSON.parse(readFileSync(PERSIST_FILE, 'utf8'));
if (raw && typeof raw === 'object' && raw.model && raw.baseUrl) {
return raw as OllamaRuntimeConfig;
}
} catch {
/* ignore unreadable/corrupt file */
}
return null;
}