Files
OmniRoute/src/lib/skills/registry.ts
Diego Rodrigues de Sa e Souza 3432dfd280 Release v3.6.9 (#1404)
* test: resolve typescript strictness complaints in unit tests

* Update Claude Code obfuscation to version 2.1.114 (#1403)

* fix(cloud-code): scope thinking stripping to executor boundaries (#1401)

* fix(cloud-code): scope thinking stripping to executors

* fix(cloud-code): guard antigravity normalized body

* Update Claude Code obfuscation to version 2.1.114

- Update Claude Code version from 2.1.87 to 2.1.114
- Update X-Stainless-Package-Version from 0.80.0 to 0.81.0
- Add new beta flags: redact-thinking-2026-02-12, advisor-tool-2026-03-01, advanced-tool-use-2025-11-20
- Add missing headers: anthropic-version, anthropic-dangerous-direct-browser-access, x-app, X-Stainless-Timeout
- Add all X-Stainless-* headers (Arch, Lang, OS, Runtime, Runtime-Version, Retry-Count)
- Fix accept-encoding header: identity -> gzip, deflate, br, zstd
- Add connection: keep-alive header
- Update tool name mapping: add lsp, apply_patch, websearch

These changes ensure that requests from OpenCode through Omniroute are indistinguishable from genuine Claude Code 2.1.114 requests, allowing proper authentication with Anthropic's API without triggering extra credits errors.

* fix: resolve CodeQL password hash alert and TruffleHog CI failure

---------

Co-authored-by: Randi <55005611+rdself@users.noreply.github.com>
Co-authored-by: Diego Rodrigues de Sa e Souza <8016841+diegosouzapw@users.noreply.github.com>
Co-authored-by: Nikolay Popov <ekklesio.dev@gmail.com>
Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>

* fix(claude-code): scope obfuscation to cli clients and fix tests

* docs(workflows): enforce PR merge instead of manual close

* docs(changelog): update 3.6.9 notes with missing PR 1403 and fixes

* docs(workflows): update generate-release to use full changelog for PR body

* fix(tsc): silence baseUrl deprecation warnings for TS 5.5+

* fix(chatcore): apply proactive compression before provider translation (#1406)

Integrated into release/v3.6.9

* docs(changelog): add PR 1406

* Makes text visible in dark-mode (#1409)

Integrated into release/v3.6.9

* docs(changelog): add PR 1409

* chore: save local work

* chore(release): sync version references to 3.6.9

* fix(codex): prevent proactive token refresh consumption and strip background parameter

* ci: shard long-running suites and relax timeouts

* ci: allow manual CI dispatch for release branches

* feat(skills): provider-aware marketplace UX, scored AUTO injection, and memory pipeline hardening (#1411)

* fix/400 for GeminiCLI(add "ref" in GEMINI_UNSUPPORTED_SCHEMA_KEYS)

* feat(cc-compatible): align request shape with Claude CLI

* fix(cc-compatible): add Claude CLI system skeleton for OpenAI input

* preserve reasoning when translating chat to responses (#1414)

Integrated into release/v3.6.9

* fix(skills): optimize AUTO scoring and include Responses input context (#1418)

Integrated into release/v3.6.9

* chore: fix TS errors and update review-prs workflow

* fix(api): stop sending unsupported Gemini and Codex parameters

Prevent Gemini request translation from injecting default
thoughtSignature values that the upstream API strictly validates and
rejects. Only preserve real signatures resolved from prior upstream
responses, and strip additionalProperties from Gemini function schemas
to avoid 400 "Unknown name" errors.

Also remove fallback-injected session_id and conversation_id fields
before sending Codex requests, and restore compatibility with the
legacy OUTBOUND_SSRF_GUARD_ENABLED flag when determining whether
private provider URLs are allowed.

Updates the Gemini translator and regression tests for issue #1410
and related 400 error cases.

* fix(core): stabilization fixes for token refresh, usage translation, and testing

- Update Codex token refresh detection logic
- Mark provider connections invalid on unrecoverable refresh error
- Fix Claude usage translation under-reporting cached tokens
- Update test expectations
- Update CHANGELOG.md for v3.6.9

* fix(auth): reload fresh token state and unify expiry persistence

Refresh checks now re-read the latest stored provider connection before
attempting rotation so they do not use stale refresh tokens captured by
an earlier sweep.

Token updates also persist both expiresAt and tokenExpiresAt across the
health check, usage-limit refresh path, and SSE refresh flow. This keeps
known token expiry metadata in sync and avoids interval-based refreshes
for connections whose tokens are still valid well into the future.

* fix: resolve SSRF environment static evaluation bug (#1427)

Fix import aliases and strict TS typings for tests and ACP agents.

* test: resolve remaining strict type errors in test files

* test: fix provider service assertion for anthropic-compatible header

* fix(codex): respect openaiStoreEnabled setting during native passthrough (#1432)

* fix(codex): fix token refresh unrecoverable detection for expired tokens

* fix(ci): restore release v3.6.9 build and flaky tests

* fix(cc-compatible): trim default OpenAI system skeleton (#1433)

Integrated into release/v3.6.9

* fix: prevent masked API keys from being written to CLI tool configs (#1435)

* feat: mark Qwen provider as deprecated and add deprecation warning to CLI tool (#1437)

* docs(changelog): comprehensive v3.6.9 update with all 59 commits since v3.6.8

* test(ci): align qwen guide settings assertions

* fix(security): resolve CodeQL alert 163 for incomplete URL sanitization in Qwen CLI settings

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
Co-authored-by: Nikolay Popov <74762779+nikolay-popov-ideogram@users.noreply.github.com>
Co-authored-by: Randi <55005611+rdself@users.noreply.github.com>
Co-authored-by: Nikolay Popov <ekklesio.dev@gmail.com>
Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com>
Co-authored-by: Tim Massey <tim-massey@users.noreply.github.com>
Co-authored-by: Paijo <oyi77@users.noreply.github.com>
Co-authored-by: dail45 <dail45@yandex.ru>
Co-authored-by: R.D. <rogerproself@gmail.com>
2026-04-19 19:50:30 -03:00

320 lines
10 KiB
TypeScript

import { Skill, SkillSchema } from "./types";
import { SkillCreateInputSchema } from "./schemas";
import { getDbInstance } from "../db/core";
import { randomUUID } from "crypto";
import { logger } from "../../../open-sse/utils/logger.ts";
const log = logger("SKILLS");
class SkillRegistry {
private static instance: SkillRegistry;
private registeredSkills: Map<string, Skill> = new Map();
private versionCache: Map<string, Map<string, Skill>> = new Map();
private lastLoaded: number = 0;
private readonly cacheTTL: number = 60_000; // 60 seconds
private pendingLoad: Promise<void> | null = null; // dedupes concurrent cache fills
private constructor() {}
static getInstance(): SkillRegistry {
if (!SkillRegistry.instance) {
SkillRegistry.instance = new SkillRegistry();
}
return SkillRegistry.instance;
}
private isCacheStale(): boolean {
return Date.now() - this.lastLoaded > this.cacheTTL;
}
invalidateCache(): void {
this.lastLoaded = 0;
}
async register(skillData: {
name: string;
version?: string;
description?: string;
schema: SkillSchema;
handler: string;
enabled?: boolean;
apiKeyId: string;
mode?: "on" | "off" | "auto";
sourceProvider?: "skillsmp" | "skillssh" | "local";
tags?: string[];
installCount?: number;
}): Promise<Skill> {
const {
apiKeyId: _apiKeyId,
mode: _mode,
sourceProvider: _sourceProvider,
tags: _tags,
installCount: _installCount,
...parseableData
} = skillData;
const parsed = SkillCreateInputSchema.parse(parseableData);
const db = getDbInstance();
const id = randomUUID();
const now = new Date();
db.prepare(
`INSERT INTO skills (id, api_key_id, name, version, description, schema, handler, enabled, mode, source_provider, tags, install_count, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
).run(
id,
skillData.apiKeyId,
parsed.name,
parsed.version,
parsed.description || null,
JSON.stringify(parsed.schema),
parsed.handler,
parsed.enabled ? 1 : 0,
skillData.mode || (parsed.enabled ? "on" : "off"),
skillData.sourceProvider || null,
JSON.stringify(skillData.tags || []),
typeof skillData.installCount === "number" ? Math.max(0, skillData.installCount) : 0,
now.toISOString(),
now.toISOString()
);
const skill: Skill = {
id,
apiKeyId: skillData.apiKeyId,
name: parsed.name,
version: parsed.version,
description: parsed.description || "",
schema: parsed.schema,
handler: parsed.handler,
enabled: parsed.enabled,
mode: skillData.mode || (parsed.enabled ? "on" : "off"),
sourceProvider: skillData.sourceProvider,
tags: skillData.tags || [],
installCount:
typeof skillData.installCount === "number" ? Math.max(0, skillData.installCount) : 0,
createdAt: now,
updatedAt: now,
};
this.registeredSkills.set(`${parsed.name}@${parsed.version}`, skill);
this.updateVersionCache(skill);
this.invalidateCache();
return skill;
}
async unregister(name: string, version?: string, apiKeyId?: string): Promise<boolean> {
const db = getDbInstance();
if (version) {
const key = `${name}@${version}`;
const skill = this.registeredSkills.get(key);
if (skill && (!apiKeyId || skill.apiKeyId === apiKeyId)) {
db.prepare("DELETE FROM skills WHERE id = ?").run(skill.id);
this.registeredSkills.delete(key);
this.rebuildVersionCache(name);
this.invalidateCache();
return true;
}
} else {
const deleted = db
.prepare("DELETE FROM skills WHERE name = ? AND (? IS NULL OR api_key_id = ?)")
.run(name, apiKeyId || null, apiKeyId || null);
if (deleted.changes > 0) {
const keysToDelete = Array.from(this.registeredSkills.entries())
.filter(([, skill]) => skill.name === name && (!apiKeyId || skill.apiKeyId === apiKeyId))
.map(([key]) => key);
keysToDelete.forEach((k) => this.registeredSkills.delete(k));
this.rebuildVersionCache(name);
this.invalidateCache();
return true;
}
}
return false;
}
async unregisterById(id: string): Promise<boolean> {
const db = getDbInstance();
const deleted = db.prepare("DELETE FROM skills WHERE id = ?").run(id);
if (deleted.changes > 0) {
const affectedNames = new Set<string>();
const keysToDelete = Array.from(this.registeredSkills.entries())
.filter(([, skill]) => skill.id === id)
.map(([key, skill]) => {
affectedNames.add(skill.name);
return key;
});
keysToDelete.forEach((k) => this.registeredSkills.delete(k));
affectedNames.forEach((name) => this.rebuildVersionCache(name));
this.invalidateCache();
return true;
}
return false;
}
list(apiKeyId?: string): Skill[] {
log.debug("skills.registry.list", { apiKeyId, cached: !this.isCacheStale() });
if (apiKeyId) {
return Array.from(this.registeredSkills.values()).filter((s) => s.apiKeyId === apiKeyId);
}
return Array.from(this.registeredSkills.values());
}
getSkill(name: string, _apiKeyId?: string): Skill | undefined {
return this.registeredSkills.get(name);
}
getSkillVersions(name: string): Skill[] {
const cached = this.versionCache.get(name);
if (!cached) return [];
return Array.from(cached.values()).sort((a, b) => this.compareVersions(b.version, a.version));
}
resolveVersion(name: string, constraint: string, _apiKeyId?: string): Skill | undefined {
const versions = this.getSkillVersions(name);
if (versions.length === 0) return undefined;
const operator = constraint.charAt(0);
const version = constraint.slice(1);
switch (operator) {
case "^":
return versions.find((s) => this.satisfies(s.version, version, "^"));
case "~":
return versions.find((s) => this.satisfies(s.version, version, "~"));
case ">":
case ">=":
case "<":
case "<=":
case "==":
return versions.find((s) => this.satisfies(s.version, version, operator));
default:
return versions.find((s) => s.version === constraint);
}
}
private satisfies(version: string, base: string, operator: string): boolean {
const [baseMajor, baseMinor, basePatch] = base.split(".").map(Number);
const [verMajor, verMinor, verPatch] = version.split(".").map(Number);
switch (operator) {
case "^":
return (
verMajor === baseMajor &&
(verMinor > baseMinor || (verMinor === baseMinor && verPatch >= basePatch))
);
case "~":
return verMajor === baseMajor && verMinor === baseMinor && verPatch >= basePatch;
case ">":
return this.compareVersions(version, base) > 0;
case ">=":
return this.compareVersions(version, base) >= 0;
case "<":
return this.compareVersions(version, base) < 0;
case "<=":
return this.compareVersions(version, base) <= 0;
case "==":
return version === base;
default:
return version === base;
}
}
private compareVersions(a: string, b: string): number {
const [aMajor, aMinor, aPatch] = a.split(".").map(Number);
const [bMajor, bMinor, bPatch] = b.split(".").map(Number);
if (aMajor !== bMajor) return aMajor - bMajor;
if (aMinor !== bMinor) return aMinor - bMinor;
return aPatch - bPatch;
}
private updateVersionCache(skill: Skill): void {
if (!this.versionCache.has(skill.name)) {
this.versionCache.set(skill.name, new Map());
}
this.versionCache.get(skill.name)!.set(skill.version, skill);
}
private clearVersionCache(name: string): void {
this.versionCache.delete(name);
}
private rebuildVersionCache(name: string): void {
this.clearVersionCache(name);
for (const skill of this.registeredSkills.values()) {
if (skill.name === name) {
this.updateVersionCache(skill);
}
}
}
async loadFromDatabase(apiKeyId?: string): Promise<void> {
if (this.pendingLoad) {
await this.pendingLoad;
return;
}
if (!this.isCacheStale()) return;
this.pendingLoad = (async () => {
try {
log.debug("skills.registry.loadFromDatabase", { cached: false });
const db = getDbInstance();
const rows = apiKeyId
? db.prepare("SELECT * FROM skills WHERE api_key_id = ?").all(apiKeyId)
: db.prepare("SELECT * FROM skills").all();
for (const row of rows as any[]) {
const tags = (() => {
try {
if (typeof row.tags !== "string") return [];
const parsed = JSON.parse(row.tags);
return Array.isArray(parsed) ? parsed.filter((item) => typeof item === "string") : [];
} catch {
return [];
}
})();
const skill: Skill = {
id: row.id,
apiKeyId: row.api_key_id,
name: row.name,
version: row.version,
description: row.description || "",
schema: JSON.parse(row.schema),
handler: row.handler,
enabled: row.enabled === 1,
mode: row.mode === "off" || row.mode === "auto" ? row.mode : "on",
sourceProvider:
row.source_provider === "skillsmp" || row.source_provider === "skillssh"
? row.source_provider
: row.source_provider
? "local"
: undefined,
tags,
installCount: typeof row.install_count === "number" ? row.install_count : 0,
createdAt: new Date(row.created_at),
updatedAt: new Date(row.updated_at),
};
this.registeredSkills.set(`${skill.name}@${skill.version}`, skill);
this.updateVersionCache(skill);
}
this.lastLoaded = Date.now();
} catch (err: any) {
log.error("loadFromDatabase error:", err);
throw err;
} finally {
this.pendingLoad = null;
}
})();
try {
await this.pendingLoad;
} finally {
this.pendingLoad = null;
}
}
}
export const skillRegistry = SkillRegistry.getInstance();