feat(new): harden skill revisions
This commit is contained in:
1 parent
9aa4bdf600
commit
04e77d8905
7 files changed
+296
-68
No files matched your search
@@ -1,79 +1,39 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
||||
import { basename, join } from "node:path";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import type { BindSkillInput, ImportSkillDirectoryInput, ResolveAgentSkillsInput } from "../../shared/commands";
|
||||
import { createId } from "../../shared/ids";
|
||||
import { AuditService } from "./audit-service";
|
||||
|
||||
interface SkillManifest {
|
||||
name: string;
|
||||
version: string;
|
||||
entrypoint: string;
|
||||
capabilities: string[];
|
||||
requiredTools: string[];
|
||||
compatibleModels: string[];
|
||||
riskLevel: string;
|
||||
}
|
||||
import { copySkillRevision, recursiveSkillChecksum } from "./skill-artifacts";
|
||||
import { loadSkillManifest, type SkillManifest } from "./skill-manifest";
|
||||
|
||||
function slugify(value: string): string {
|
||||
return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
||||
}
|
||||
|
||||
function parseSkillName(markdown: string, directoryPath: string): string {
|
||||
const frontmatterName = markdown.match(/^---[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?/m)?.[1];
|
||||
if (frontmatterName) return frontmatterName.trim();
|
||||
const heading = markdown.match(/^#\s+(.+)$/m)?.[1];
|
||||
return heading?.trim() || basename(directoryPath);
|
||||
}
|
||||
|
||||
function hashFiles(directoryPath: string): string {
|
||||
const hash = createHash("sha256");
|
||||
const files = readdirSync(directoryPath).filter((name) => !name.startsWith(".")).sort();
|
||||
for (const file of files) {
|
||||
const path = join(directoryPath, file);
|
||||
const stats = statSync(path);
|
||||
if (stats.isFile()) {
|
||||
hash.update(file);
|
||||
hash.update(readFileSync(path));
|
||||
}
|
||||
}
|
||||
return hash.digest("hex");
|
||||
}
|
||||
|
||||
export class SkillService {
|
||||
private readonly audit: AuditService;
|
||||
|
||||
constructor(private readonly db: DatabaseSync) {
|
||||
constructor(private readonly db: DatabaseSync, private readonly artifactRoot: string) {
|
||||
this.audit = new AuditService(db);
|
||||
}
|
||||
|
||||
importDirectory(input: ImportSkillDirectoryInput): string {
|
||||
const skillPath = join(input.directoryPath, "SKILL.md");
|
||||
if (!existsSync(skillPath)) throw new Error("SKILL.md was not found in the selected directory.");
|
||||
const markdown = readFileSync(skillPath, "utf8");
|
||||
const name = parseSkillName(markdown, input.directoryPath);
|
||||
const slug = slugify(name);
|
||||
const manifest = loadSkillManifest(input.directoryPath, input.versionSemver);
|
||||
const slug = slugify(manifest.name);
|
||||
if (!slug) throw new Error("Skill name could not be derived.");
|
||||
const now = new Date().toISOString();
|
||||
const skillId = createId("skl");
|
||||
const revisionId = createId("skr");
|
||||
const checksum = hashFiles(input.directoryPath);
|
||||
const manifest: SkillManifest = {
|
||||
name,
|
||||
version: input.versionSemver,
|
||||
entrypoint: "SKILL.md",
|
||||
capabilities: [],
|
||||
requiredTools: [],
|
||||
compatibleModels: ["openai/*", "anthropic/*", "xai/*"],
|
||||
riskLevel: "medium",
|
||||
};
|
||||
const checksum = recursiveSkillChecksum(input.directoryPath);
|
||||
const copiedFiles = copySkillRevision(input.directoryPath, this.artifactRoot, revisionId);
|
||||
const copiedEntrypoint = copiedFiles.find((file) => file.relativePath === manifest.entrypoint);
|
||||
if (!copiedEntrypoint) throw new Error("Skill manifest entrypoint was not found.");
|
||||
|
||||
this.db.prepare(`
|
||||
insert into skill_definitions(id, org_id, slug, name, owner_type, status, created_at)
|
||||
values (?, ?, ?, ?, ?, ?, ?)
|
||||
on conflict(org_id, slug) do update set name = excluded.name, status = 'active'
|
||||
`).run(skillId, input.orgId, slug, name, "organization", "active", now);
|
||||
`).run(skillId, input.orgId, slug, manifest.name, "organization", "active", now);
|
||||
|
||||
const existing = this.db.prepare("select id from skill_definitions where org_id = ? and slug = ?")
|
||||
.get(input.orgId, slug) as { id: string };
|
||||
@@ -85,17 +45,25 @@ export class SkillService {
|
||||
`).run(
|
||||
revisionId,
|
||||
existing.id,
|
||||
input.versionSemver,
|
||||
manifest.version,
|
||||
JSON.stringify(manifest),
|
||||
"local_directory",
|
||||
input.directoryPath,
|
||||
now,
|
||||
checksum,
|
||||
);
|
||||
this.db.prepare(`
|
||||
insert into skill_artifacts(id, revision_id, artifact_type, object_key, sha256, size_bytes)
|
||||
values (?, ?, ?, ?, ?, ?)
|
||||
`).run(createId("ska"), revisionId, "markdown", skillPath, checksum, Buffer.byteLength(markdown));
|
||||
for (const file of copiedFiles) {
|
||||
this.db.prepare(`
|
||||
insert into skill_artifacts(id, revision_id, artifact_type, object_key, sha256, size_bytes)
|
||||
values (?, ?, ?, ?, ?, ?)
|
||||
`).run(createId("ska"), revisionId, artifactType(file.relativePath, manifest), file.objectKey, file.sha256, file.sizeBytes);
|
||||
}
|
||||
for (const testPath of manifest.tests) {
|
||||
this.db.prepare(`
|
||||
insert into skill_tests(id, revision_id, test_type, expected_output_ref, last_result, last_run_at)
|
||||
values (?, ?, ?, ?, ?, ?)
|
||||
`).run(createId("skt"), revisionId, "manifest", testPath, null, null);
|
||||
}
|
||||
|
||||
this.audit.record({
|
||||
orgId: input.orgId,
|
||||
@@ -104,18 +72,28 @@ export class SkillService {
|
||||
actorType: "system",
|
||||
actorId: null,
|
||||
action: "published",
|
||||
payload: { slug, version: input.versionSemver },
|
||||
payload: { slug, version: manifest.version },
|
||||
});
|
||||
return revisionId;
|
||||
}
|
||||
|
||||
bind(input: BindSkillInput): string {
|
||||
const id = createId("skb");
|
||||
this.db.prepare(`
|
||||
insert into skill_bindings(id, org_id, agent_id, skill_id, pinned_revision_id, binding_mode, priority, enabled)
|
||||
values (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
on conflict(agent_id, skill_id) do update set pinned_revision_id = excluded.pinned_revision_id, enabled = 1
|
||||
`).run(id, input.orgId, input.agentId, input.skillId, input.revisionId, "pinned", 100, 1);
|
||||
this.verifyBindingTargets(input);
|
||||
const existing = this.db.prepare("select id from skill_bindings where agent_id = ? and skill_id = ?")
|
||||
.get(input.agentId, input.skillId) as { id: string } | undefined;
|
||||
const id = existing?.id ?? createId("skb");
|
||||
if (existing) {
|
||||
this.db.prepare(`
|
||||
update skill_bindings
|
||||
set pinned_revision_id = ?, binding_mode = ?, priority = ?, enabled = ?
|
||||
where id = ? and org_id = ?
|
||||
`).run(input.revisionId, "pinned", 100, 1, id, input.orgId);
|
||||
} else {
|
||||
this.db.prepare(`
|
||||
insert into skill_bindings(id, org_id, agent_id, skill_id, pinned_revision_id, binding_mode, priority, enabled)
|
||||
values (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(id, input.orgId, input.agentId, input.skillId, input.revisionId, "pinned", 100, 1);
|
||||
}
|
||||
this.audit.record({
|
||||
orgId: input.orgId,
|
||||
entityType: "skill_binding",
|
||||
@@ -132,6 +110,9 @@ export class SkillService {
|
||||
const agent = this.db.prepare("select id from agents where id = ? and org_id = ?")
|
||||
.get(input.agentId, input.orgId) as { id: string } | undefined;
|
||||
if (!agent) throw new Error("Agent was not found.");
|
||||
const existingSnapshot = this.db.prepare("select id from skill_runtime_snapshots where agent_id = ? and run_id = ?")
|
||||
.get(input.agentId, input.runId) as { id: string } | undefined;
|
||||
if (existingSnapshot) throw new Error("Skill runtime snapshot already exists for this run.");
|
||||
const rows = this.db.prepare(`
|
||||
select
|
||||
sr.id as revision_id,
|
||||
@@ -140,7 +121,7 @@ export class SkillService {
|
||||
sa.object_key
|
||||
from skill_bindings sb
|
||||
join skill_revisions sr on sr.id = sb.pinned_revision_id
|
||||
join skill_artifacts sa on sa.revision_id = sr.id and sa.artifact_type = 'markdown'
|
||||
join skill_artifacts sa on sa.revision_id = sr.id and sa.artifact_type in ('entrypoint', 'markdown')
|
||||
where sb.org_id = ? and sb.agent_id = ? and sb.enabled = 1
|
||||
order by sb.priority asc, sr.published_at asc
|
||||
`).all(input.orgId, input.agentId) as unknown as RuntimeSkillRow[];
|
||||
@@ -187,6 +168,25 @@ export class SkillService {
|
||||
});
|
||||
return snapshotId;
|
||||
}
|
||||
|
||||
private verifyBindingTargets(input: BindSkillInput): void {
|
||||
const agent = this.db.prepare("select id from agents where id = ? and org_id = ?")
|
||||
.get(input.agentId, input.orgId) as { id: string } | undefined;
|
||||
if (!agent) throw new Error("Agent was not found.");
|
||||
const skill = this.db.prepare("select id from skill_definitions where id = ? and org_id = ?")
|
||||
.get(input.skillId, input.orgId) as { id: string } | undefined;
|
||||
if (!skill) throw new Error("Skill was not found.");
|
||||
const revision = this.db.prepare("select id from skill_revisions where id = ? and skill_id = ?")
|
||||
.get(input.revisionId, input.skillId) as { id: string } | undefined;
|
||||
if (!revision) throw new Error("Skill revision was not found.");
|
||||
}
|
||||
}
|
||||
|
||||
function artifactType(relativePath: string, manifest: SkillManifest): string {
|
||||
if (relativePath === "skill.manifest.json") return "manifest";
|
||||
if (relativePath === manifest.entrypoint) return "entrypoint";
|
||||
if (manifest.tests.includes(relativePath)) return "test";
|
||||
return "asset";
|
||||
}
|
||||
|
||||
interface RuntimeSkillRow {
|
||||
|
||||
Reference in new issue
Block a user