omp-config-crypt 0.6.3 → 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omp-config-crypt",
3
- "version": "0.6.3",
3
+ "version": "0.6.4",
4
4
  "description": "Universal cross-platform encrypted portability for omp config, extensions, and instructions",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -36,5 +36,8 @@
36
36
  "extensions": [
37
37
  "./index.js"
38
38
  ]
39
+ },
40
+ "dependencies": {
41
+ "yaml": "2.9.1"
39
42
  }
40
43
  }
@@ -43,6 +43,23 @@ export function pruneOldBackups(agentDir, keepCount = 3) {
43
43
  const pruned = [];
44
44
  if (!fs.existsSync(agentDir)) return pruned;
45
45
 
46
+ const recoveryLock = path.join(agentDir, ".sync-recovery.local.lock");
47
+ if (fs.existsSync(recoveryLock)) return pruned;
48
+
49
+ let activeBackup = null;
50
+ const lockPath = path.join(agentDir, ".sync.local.lock");
51
+ if (fs.existsSync(lockPath)) {
52
+ try {
53
+ const lock = JSON.parse(fs.readFileSync(lockPath, "utf8"));
54
+ if (typeof lock?.backupDir === "string" && lock.backupDir) {
55
+ activeBackup = lock.backupDir;
56
+ }
57
+ } catch {
58
+ // Corrupt lock: do not prune anything that might still be referenced.
59
+ return pruned;
60
+ }
61
+ }
62
+
46
63
  const entries = fs.readdirSync(agentDir, { withFileTypes: true });
47
64
  const backups = entries
48
65
  .filter((e) => e.isDirectory() && e.name.startsWith(".import-backup-"))
@@ -50,8 +67,20 @@ export function pruneOldBackups(agentDir, keepCount = 3) {
50
67
  .sort()
51
68
  .reverse();
52
69
 
53
- if (backups.length > keepCount) {
54
- const toRemove = backups.slice(keepCount);
70
+ const eligibleBackups = backups.filter((name) => {
71
+ if (activeBackup && name === activeBackup) return false;
72
+ const journalFile = path.join(agentDir, name, "journal.json");
73
+ if (!fs.existsSync(journalFile)) return false;
74
+ try {
75
+ const journal = JSON.parse(fs.readFileSync(journalFile, "utf8"));
76
+ return journal?.status === "completed";
77
+ } catch {
78
+ return false;
79
+ }
80
+ });
81
+
82
+ if (eligibleBackups.length > keepCount) {
83
+ const toRemove = eligibleBackups.slice(keepCount);
55
84
  for (const name of toRemove) {
56
85
  const fullPath = path.join(agentDir, name);
57
86
  try {
@@ -69,7 +98,6 @@ export function pruneOldBackups(agentDir, keepCount = 3) {
69
98
  export function cleanObsoleteFiles(agentDir) {
70
99
  const ompDir = getOmpHome(agentDir);
71
100
  const targets = [
72
- path.join(agentDir, "models.local.json"),
73
101
  path.join(ompDir, "extensions", "local-models.js"),
74
102
  path.join(ompDir, "extensions", "agy.js"),
75
103
  ];
package/src/prober.js CHANGED
@@ -16,6 +16,19 @@ const NON_CHAT_PATTERNS = [
16
16
  /stable-diffusion/i,
17
17
  /upscale/i,
18
18
  /realtime/i,
19
+ /sdxl/i,
20
+ /imagen/i,
21
+ /ideogram/i,
22
+ /kolors/i,
23
+ /sora/i,
24
+ /kling/i,
25
+ /cogvideo/i,
26
+ /runway/i,
27
+ /luma/i,
28
+ /pika/i,
29
+ /vidu/i,
30
+ /wanx/i,
31
+ /(?:^|[-_./])(?:image|video|t2i|t2v|i2v)(?:[-_./]|$)/i,
19
32
  ];
20
33
 
21
34
  /**
@@ -38,38 +51,42 @@ export function inferModelCapabilities(modelId, providerHint = "") {
38
51
 
39
52
  // Reasoning detection
40
53
  const isReasoning =
41
- /(thinking|reasoner|reasoning|deepseek-r1|\br1\b|\bo1\b|\bo3\b|-high\b|-thought\b)/i.test(id);
54
+ /(thinking|reasoner|reasoning|deepseek-r1|\br1\b|\bo1\b|\bo3\b|-high\b|-thought\b|sol|terra)/i.test(id);
42
55
 
43
56
  // Vision / Multimodal detection
44
57
  const isVision =
45
58
  /(vision|\bvl\b|omni|\b4o\b|flash|gemini|claude|sonnet|opus|qwen-vl|glm-4v)/i.test(id);
46
59
 
47
- // Context window heuristics
48
- let contextWindow = 128000;
49
- if (/gemini-1\.5|gemini-2\.0|gemini-3\.0|gemini-3\.5|gemini-3\.8/i.test(id)) {
50
- contextWindow = /pro/i.test(id) ? 1000000 : 256000;
51
- } else if (/claude-3/i.test(id)) {
52
- contextWindow = 200000;
60
+ // Context window heuristics (默认 256K 兜底)
61
+ let contextWindow = 256000;
62
+ if (/gemini.*pro/i.test(id)) {
63
+ contextWindow = 2000000;
64
+ } else if (/gemini/i.test(id)) {
65
+ contextWindow = 1000000;
66
+ } else if (/deepseek/i.test(id)) {
67
+ contextWindow = 1048576;
53
68
  } else if (/kimi|moonshot/i.test(id)) {
69
+ contextWindow = 512000;
70
+ } else if (/claude/i.test(id)) {
71
+ contextWindow = 200000;
72
+ } else if (/(gpt-6|gpt-5\.[0-9]).*(sol|terra|astra)/i.test(id)) {
54
73
  contextWindow = 256000;
55
- } else if (/deepseek/i.test(id)) {
56
- contextWindow = 128000;
57
74
  } else if (/qwen/i.test(id)) {
58
75
  contextWindow = /32b|72b|128k/i.test(id) ? 131072 : 65536;
59
- } else if (/glm-4/i.test(id)) {
60
- contextWindow = 128000;
76
+ } else if (/glm-5/i.test(id)) {
77
+ contextWindow = 1048576;
61
78
  }
62
79
 
63
80
  // Max output tokens heuristics
64
- let maxTokens = 32000;
65
- if (/claude-3-5|claude-3-7/i.test(id)) {
66
- maxTokens = 8192;
67
- } else if (/gpt-4o/i.test(id)) {
68
- maxTokens = 16384;
69
- } else if (/qwen/i.test(id)) {
70
- maxTokens = 8192;
71
- } else if (contextWindow <= 65536) {
72
- maxTokens = Math.min(maxTokens, 8192);
81
+ let maxTokens = 65536;
82
+ if (/(sol|terra)/i.test(id)) {
83
+ maxTokens = 384000;
84
+ } else if (/claude/i.test(id)) {
85
+ maxTokens = 64000;
86
+ } else if (/deepseek/i.test(id)) {
87
+ maxTokens = 65536;
88
+ } else if (/kimi|moonshot/i.test(id)) {
89
+ maxTokens = 32000;
73
90
  }
74
91
 
75
92
  // Formatting display name
@@ -97,164 +114,180 @@ export function inferModelCapabilities(modelId, providerHint = "") {
97
114
  return spec;
98
115
  }
99
116
 
100
- /**
101
- * Probe an endpoint to find the working baseUrl, API flavor, and available models.
102
- */
103
- export async function probeProvider({
104
- baseUrl,
105
- apiKey,
106
- api = "openai-completions",
107
- testModelId,
108
- providerName = "",
109
- timeout = 10000,
110
- }) {
111
- let cleanUrl = (baseUrl || "").trim().replace(/\/+$/, "");
112
- if (!cleanUrl) {
113
- return { ok: false, error: "Missing baseUrl" };
114
- }
117
+ const APIS = ["openai-completions", "openai-responses", "anthropic-messages"];
115
118
 
116
- const controller = new AbortController();
117
- const timer = setTimeout(() => controller.abort(), timeout);
119
+ function safeError(value, apiKey) {
120
+ let text = String(value || "Invalid upstream response");
121
+ if (apiKey) text = text.split(apiKey).join("[redacted]");
122
+ return text.replace(/Bearer\s+[^\s"',}]+/gi, "[redacted]")
123
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").slice(0, 400);
124
+ }
125
+
126
+ function jsonText(json, api) {
127
+ if (api === "openai-completions") {
128
+ return json?.choices?.some(choice => choice.finish_reason != null &&
129
+ typeof choice.message?.content === "string" && choice.message.content.trim());
130
+ }
131
+ if (api === "openai-responses") {
132
+ return json?.status === "completed" && (typeof json.output_text === "string" && json.output_text.trim() ||
133
+ json.output?.some(item => item.content?.some(part => part.type === "output_text" && typeof part.text === "string" && part.text.trim())));
134
+ }
135
+ return json?.type === "message" && json.stop_reason != null &&
136
+ json.content?.some(part => part.type === "text" && typeof part.text === "string" && part.text.trim());
137
+ }
118
138
 
139
+ async function readGeneration(response, api) {
140
+ if (!response.headers.get("content-type")?.includes("text/event-stream")) {
141
+ const json = await response.json();
142
+ if (json?.error || !jsonText(json, api)) throw new Error("Generation did not complete with text output");
143
+ return;
144
+ }
145
+ if (!response.body) throw new Error("Empty response stream");
146
+ const reader = response.body.getReader();
147
+ const decoder = new TextDecoder();
148
+ let buffer = "", text = "", finished = false, complete = false;
149
+ const consume = frame => {
150
+ const lines = frame.split(/\r?\n/);
151
+ const event = lines.find(line => line.startsWith("event:"))?.slice(6).trim();
152
+ const data = lines.filter(line => line.startsWith("data:")).map(line => line.slice(5).trimStart()).join("\n");
153
+ if (!data) return;
154
+ if (data === "[DONE]") {
155
+ if (api === "openai-completions" && finished) complete = true;
156
+ return;
157
+ }
158
+ const json = JSON.parse(data);
159
+ const type = json.type || event;
160
+ if (json.error || ["error", "response.failed", "response.incomplete"].includes(type)) {
161
+ throw new Error(JSON.stringify(json.error || json));
162
+ }
163
+ if (api === "openai-completions") {
164
+ // Validate the primary choice, never combine output and termination from different choices.
165
+ const choice = json.choices?.find(item => item.index === undefined || item.index === 0);
166
+ if (typeof choice?.delta?.content === "string") text += choice.delta.content;
167
+ if (choice?.finish_reason != null) finished = true;
168
+ } else if (api === "openai-responses") {
169
+ if (type === "response.output_text.delta" && typeof json.delta === "string") text += json.delta;
170
+ if (type === "response.completed") {
171
+ if (json.response?.status && json.response.status !== "completed") throw new Error("Response not completed");
172
+ if (json.response?.error) throw new Error(JSON.stringify(json.response.error));
173
+ if (jsonText(json.response, api)) text += json.response.output_text || json.response.output
174
+ ?.flatMap(item => item.content || []).filter(part => part.type === "output_text").map(part => part.text).join("") || "";
175
+ complete = true;
176
+ }
177
+ } else {
178
+ if (type === "content_block_start" && json.content_block?.type === "text") text += json.content_block.text || "";
179
+ if (type === "content_block_delta" && json.delta?.type === "text_delta") text += json.delta.text || "";
180
+ if (type === "message_stop") complete = true;
181
+ }
182
+ };
119
183
  try {
120
- if (api === "anthropic-messages") {
121
- // Probe Anthropic endpoint
122
- const res = await testAnthropic(cleanUrl, apiKey, controller.signal);
123
- clearTimeout(timer);
124
- if (res.ok) {
125
- const models = (res.models && res.models.length > 0)
126
- ? res.models.map((m) => inferModelCapabilities(m.id || m, providerName))
127
- : [inferModelCapabilities(testModelId || "claude-3-7-sonnet-20250219", providerName)];
128
- return {
129
- ok: true,
130
- normalizedBaseUrl: res.normalizedUrl,
131
- api: "anthropic-messages",
132
- models,
133
- probedVia: res.probedVia,
134
- };
184
+ for (;;) {
185
+ const chunk = await reader.read();
186
+ buffer += decoder.decode(chunk.value, { stream: !chunk.done });
187
+ let boundary;
188
+ while ((boundary = /\r?\n\r?\n/.exec(buffer))) {
189
+ consume(buffer.slice(0, boundary.index));
190
+ buffer = buffer.slice(boundary.index + boundary[0].length);
191
+ }
192
+ if (complete) {
193
+ if (!text.trim()) throw new Error("Generation completed without text output");
194
+ return;
135
195
  }
136
- return { ok: false, error: res.error || "Anthropic endpoint unreachable" };
196
+ if (chunk.done) throw new Error("Empty or truncated generation stream");
137
197
  }
198
+ } finally {
199
+ try { await reader.cancel(); } catch {}
200
+ reader.releaseLock();
201
+ }
202
+ }
138
203
 
139
- // Default to openai-completions probe
140
- // 1. Try /models endpoints first (with and without /v1)
141
- const hasV1 = /\/v1$/i.test(cleanUrl);
142
- const candidateUrls = hasV1
143
- ? [cleanUrl, cleanUrl.replace(/\/v1$/i, "")]
144
- : [cleanUrl, `${cleanUrl}/v1`];
145
-
146
- for (const url of candidateUrls) {
147
- const modelsEndpoint = `${url}/models`;
148
- try {
149
- const res = await fetch(modelsEndpoint, {
150
- method: "GET",
151
- headers: {
152
- Authorization: `Bearer ${apiKey}`,
153
- Accept: "application/json",
154
- },
155
- signal: controller.signal,
156
- });
157
-
158
- if (res.status === 200) {
159
- const json = await res.json();
160
- const rawList = Array.isArray(json?.data) ? json.data : Array.isArray(json) ? json : [];
161
- const filtered = filterChatModels(rawList);
162
- if (filtered.length > 0) {
163
- clearTimeout(timer);
164
- // In OMP, openai-completions appends /chat/completions.
165
- // If models endpoint was at ${url}/models, the baseUrl must be ${url}.
166
- return {
167
- ok: true,
168
- normalizedBaseUrl: url,
169
- api: "openai-completions",
170
- models: filtered.map((m) => inferModelCapabilities(m.id || m, providerName)),
171
- probedVia: "models_endpoint",
172
- };
173
- }
174
- }
175
- } catch {}
204
+ /** Discover model catalogs, or verify exactly one explicitly selected generation protocol. */
205
+ export async function probeProvider({
206
+ baseUrl, apiKey, api = "openai-completions", testModelId,
207
+ providerName = "", timeout = 10000, verify = false, signal,
208
+ }) {
209
+ const early = error => ({ ok: false, error, ...(verify ? { latencyMs: 0 } : {}) });
210
+ if (signal?.aborted) return { ...early("Probe cancelled"), cancelled: true, latencyMs: 0 };
211
+ if (!APIS.includes(api)) return early("Unknown API: " + safeError(api, apiKey));
212
+ if (verify && !testModelId?.trim()) return early("Generation verification requires testModelId");
213
+ const cleanUrl = (baseUrl || "").trim().replace(/\/+$/, "");
214
+ if (!cleanUrl) return early("Missing baseUrl");
215
+ const anthropic = api === "anthropic-messages";
216
+ const normalized = anthropic ? cleanUrl.replace(/\/v1$/i, "") : cleanUrl;
217
+ const controller = new AbortController();
218
+ let externallyCancelled = false, started;
219
+ const cancel = () => { externallyCancelled = true; controller.abort(); };
220
+ signal?.addEventListener("abort", cancel, { once: true });
221
+ const timer = setTimeout(() => controller.abort(), timeout);
222
+ const timing = () => verify ? { latencyMs: started === undefined ? 0 : Math.max(1, Math.round(performance.now() - started)) } : {};
223
+ let response;
224
+ const headers = { Accept: "application/json" };
225
+ if (anthropic) {
226
+ headers["anthropic-version"] = "2023-06-01";
227
+ if (apiKey) headers["x-api-key"] = apiKey;
228
+ } else if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
229
+ try {
230
+ if (verify) {
231
+ const endpoint = anthropic ? `${normalized}/v1/messages` : `${normalized}/${api === "openai-responses" ? "responses" : "chat/completions"}`;
232
+ const body = api === "openai-responses"
233
+ ? { model: testModelId, input: "Reply OK", max_output_tokens: 64, store: false, stream: true }
234
+ : { model: testModelId, messages: [{ role: "user", content: "Reply OK" }],
235
+ ...(anthropic ? { max_tokens: 64 } : { max_completion_tokens: 64 }), stream: true };
236
+ if (signal?.aborted) cancel();
237
+ if (controller.signal.aborted) throw new Error("Probe cancelled");
238
+ started = performance.now();
239
+ response = await fetch(endpoint, { method: "POST", headers: { ...headers, "Content-Type": "application/json" },
240
+ body: JSON.stringify(body), signal: controller.signal });
241
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${await readErrorBody(response)}`);
242
+ await readGeneration(response, api);
243
+ return { ok: true, normalizedBaseUrl: normalized, api,
244
+ models: [inferModelCapabilities(testModelId, providerName)], probedVia: api, verified: true, ...timing() };
176
245
  }
177
-
178
- // 2. If /models failed or returned 404, probe chat/completions directly
179
- for (const url of candidateUrls) {
180
- const chatEndpoint = `${url}/chat/completions`;
181
- const modelToTest = testModelId || "test-probe";
246
+ const candidates = anthropic ? [normalized] : /\/v1$/i.test(cleanUrl)
247
+ ? [cleanUrl, cleanUrl.replace(/\/v1$/i, "")] : [cleanUrl, `${cleanUrl}/v1`];
248
+ let lastError = "No conversational models in catalog";
249
+ for (const candidate of [...new Set(candidates)]) {
182
250
  try {
183
- const res = await fetch(chatEndpoint, {
184
- method: "POST",
185
- headers: {
186
- Authorization: `Bearer ${apiKey}`,
187
- "Content-Type": "application/json",
188
- },
189
- body: JSON.stringify({
190
- model: modelToTest,
191
- messages: [{ role: "user", content: "hi" }],
192
- max_tokens: 1,
193
- }),
194
- signal: controller.signal,
195
- });
196
-
197
- // 200 = Success; 400/404 with error JSON about model not found also confirms the endpoint exists!
198
- if (res.status === 200 || res.status === 400 || res.status === 404) {
199
- let isJsonError = false;
200
- try {
201
- const errJson = await res.json();
202
- // If it returned structured error, the endpoint is indeed an active OpenAI API!
203
- if (errJson?.error) isJsonError = true;
204
- } catch {}
205
-
206
- if (res.status === 200 || isJsonError) {
207
- clearTimeout(timer);
208
- const models = testModelId
209
- ? [inferModelCapabilities(testModelId, providerName)]
210
- : [];
211
- return {
212
- ok: true,
213
- normalizedBaseUrl: url,
214
- api: "openai-completions",
215
- models,
216
- probedVia: "chat_completions",
217
- };
218
- }
219
- }
220
- } catch {}
251
+ response = await fetch(`${candidate}${anthropic ? "/v1" : ""}/models`, { headers, signal: controller.signal });
252
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${await readErrorBody(response)}`);
253
+ const json = await response.json();
254
+ const models = filterChatModels(Array.isArray(json?.data) ? json.data : Array.isArray(json) ? json : []);
255
+ if (!models.length) throw new Error("No conversational models in catalog");
256
+ return { ok: true, normalizedBaseUrl: candidate, api,
257
+ models: models.map(m => inferModelCapabilities(m.id || m, providerName)), probedVia: "models_endpoint", verified: false };
258
+ } catch (error) {
259
+ if (controller.signal.aborted) throw error;
260
+ lastError = safeError(error.message, apiKey);
261
+ } finally {
262
+ try { await response?.body?.cancel(); } catch {}
263
+ response = undefined;
264
+ }
221
265
  }
222
-
266
+ return { ok: false, error: lastError };
267
+ } catch (error) {
268
+ return { ok: false, error: externallyCancelled ? "Probe cancelled" : controller.signal.aborted ? "Probe timed out" : safeError(error.message, apiKey),
269
+ ...(externallyCancelled ? { cancelled: true } : {}), ...timing() };
270
+ } finally {
223
271
  clearTimeout(timer);
224
- return {
225
- ok: false,
226
- error: `Could not verify OpenAI endpoint at ${cleanUrl}. Both /models and /chat/completions failed.`,
227
- };
228
- } catch (err) {
229
- clearTimeout(timer);
230
- return { ok: false, error: err.name === "AbortError" ? "Probe timed out" : err.message };
272
+ signal?.removeEventListener("abort", cancel);
273
+ try { await response?.body?.cancel(); } catch {}
231
274
  }
232
275
  }
233
276
 
234
- async function testAnthropic(cleanUrl, apiKey, signal) {
235
- const candidateUrls = [cleanUrl, `${cleanUrl}/v1`].filter((u, i, a) => a.indexOf(u) === i);
236
- for (const url of candidateUrls) {
237
- try {
238
- const endpoint = `${url}/messages`;
239
- const res = await fetch(endpoint, {
240
- method: "POST",
241
- headers: {
242
- "x-api-key": apiKey,
243
- "anthropic-version": "2023-06-01",
244
- "Content-Type": "application/json",
245
- },
246
- body: JSON.stringify({
247
- model: "claude-3-haiku-20240307",
248
- messages: [{ role: "user", content: "hi" }],
249
- max_tokens: 1,
250
- }),
251
- signal,
252
- });
253
-
254
- if (res.status === 200 || res.status === 400) {
255
- return { ok: true, normalizedUrl: url, probedVia: "messages_endpoint" };
256
- }
257
- } catch {}
277
+ async function readErrorBody(response) {
278
+ if (!response.body) return "";
279
+ const reader = response.body.getReader();
280
+ const decoder = new TextDecoder();
281
+ let text = "";
282
+ try {
283
+ while (text.length < 2048) {
284
+ const { done, value } = await reader.read();
285
+ if (done) break;
286
+ text += decoder.decode(value, { stream: true });
287
+ }
288
+ return text.slice(0, 2048);
289
+ } finally {
290
+ try { await reader.cancel(); } catch {}
291
+ reader.releaseLock();
258
292
  }
259
- return { ok: false, error: "Anthropic /messages endpoint failed" };
260
293
  }