Open source CapCut alternative.
TypeScript
feat(app): load and install skills dynamically at runtime
David Lec0850453e617
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swiftindex 5fcdde4a..ead0ceae 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swift@@ -1,8 +1,11 @@import Foundationpublic enum HarnessSkillSourceKind: String, Codable, Equatable, Sendable {+ /// Curated skill shipped inside the app bundle.case builtIn- case plugin+ /// A skill the user installed from the catalog into the on-disk install directory.+ case installed+ /// A skill the app authored by learning an app (the learned-applications directory).case userDirectorycase workspacecase remoteCatalog@@ -245,6 +248,14 @@ public struct HarnessSkillFileSystemSource: Sendable {self.sourceKind = sourceKind}+ private var validationProvenance: String {+ switch sourceKind {+ case .builtIn: return "bundleResource"+ case .installed: return "installedCatalog"+ default: return ""+ }+ }+public func discover() -> [HarnessSkillDescriptor] {roots.flatMap { root indiscover(in: root)@@ -411,18 +422,22 @@ public struct HarnessSkillFileSystemSource: Sendable {// `scripts:` IDs declared in SKILL.md (e.g. `scripts-save-note`, not// `scripts-save-note-applescript`).let relativePathWithoutExtension = (relativePath as NSString).deletingPathExtension+ // Built-in scripts are vetted in the repo; installed scripts are verified at install time+ // (checksum + optional signature) before they ever reach this directory, so both are+ // trusted-validated. Learned scripts start pending until the learning flow promotes them.+ let trustedAtRest = sourceKind == .builtIn || sourceKind == .installedreturn HarnessSkillScriptDescriptor(id: slug(relativePathWithoutExtension),language: language,purpose: titleCased(basename),relativePath: relativePath,- validationStatus: sourceKind == .builtIn ? .validated : .pendingValidation,+ validationStatus: trustedAtRest ? .validated : .pendingValidation,requiredPermissions: requiredPermissions(for: language),safetyClass: language == .appleScript ? .guardedInput : .sensitive,metadata: ["source": "filesystem","scriptDirectory": scriptsDirectory.path,- "validation.provenance": sourceKind == .builtIn ? "bundleResource" : ""+ "validation.provenance": validationProvenance])}diff --git a/apps/Donkey/Sources/DonkeyHarness/HarnessSkillManifest.swift b/apps/Donkey/Sources/DonkeyHarness/HarnessSkillManifest.swiftnew file mode 100644index 00000000..21a3112c--- /dev/null+++ b/apps/Donkey/Sources/DonkeyHarness/HarnessSkillManifest.swift@@ -0,0 +1,90 @@+import Foundation++/// The author-supplied manifest that travels with an installable skill (`manifest.json` at the+/// skill bundle root). Everything in Donkey is a skill — a folder of markdown instructions+/// (`SKILL.md`) plus optional runnable scripts — so the manifest carries only the distribution+/// metadata the install pipeline needs: identity, version, integrity, and the trust signal. The+/// operating content itself still lives in `SKILL.md`, never here.+///+/// The manifest is OPTIONAL. Built-in skills ship without one, and a downloaded skill that omits it+/// still installs — identity then falls back to the directory name and `SKILL.md` frontmatter, the+/// same way discovery already works today.+public struct HarnessSkillManifest: Codable, Equatable, Sendable {+ /// Stable identity; matches the install directory and the `id:` frontmatter in `SKILL.md`.+ public var skillID: String+ /// Semantic version of this skill bundle. Drives the versioned install layout and updates.+ public var version: String+ public var name: String?+ public var description: String?+ public var author: String?+ /// Permissions the skill's scripts need; surfaced to the user before install.+ public var requiredPermissions: [HarnessPermission]+ /// Script ids the bundle advertises (informational; discovery still reads `scripts/` from disk).+ public var scriptIDs: [String]+ /// Lowest app version this skill supports, if the author pins one.+ public var minAppVersion: String?+ /// SHA-256 of the distributed artifact, lowercase hex. Verified at install time.+ public var checksum: String?+ /// Optional cryptographic signature over the artifact (see `HarnessSkillSignature`).+ public var signature: HarnessSkillSignature?++ public init(+ skillID: String,+ version: String,+ name: String? = nil,+ description: String? = nil,+ author: String? = nil,+ requiredPermissions: [HarnessPermission] = [],+ scriptIDs: [String] = [],+ minAppVersion: String? = nil,+ checksum: String? = nil,+ signature: HarnessSkillSignature? = nil+ ) {+ self.skillID = skillID+ self.version = version+ self.name = name+ self.description = description+ self.author = author+ self.requiredPermissions = requiredPermissions+ self.scriptIDs = scriptIDs+ self.minAppVersion = minAppVersion+ self.checksum = checksum+ self.signature = signature+ }++ /// Default filename at the root of a skill bundle.+ public static let fileName = "manifest.json"++ /// Tolerant decode: a malformed or absent manifest returns nil rather than throwing, so the+ /// install/discovery paths can fall back to `SKILL.md` frontmatter.+ public static func decode(from data: Data) -> HarnessSkillManifest? {+ try? JSONDecoder().decode(HarnessSkillManifest.self, from: data)+ }++ public static func load(from url: URL) -> HarnessSkillManifest? {+ guard let data = try? Data(contentsOf: url) else { return nil }+ return decode(from: data)+ }+}++/// A signature over a distributed skill artifact. The format is intentionally provider-neutral and+/// algorithm-tagged so the real catalog's signing scheme can slot in without changing the install+/// pipeline. `ed25519` is verified with CryptoKit at install time; the public key is matched against+/// the host's set of trusted publisher keys.+public struct HarnessSkillSignature: Codable, Equatable, Sendable {+ public enum Algorithm: String, Codable, Equatable, Sendable {+ case ed25519+ }++ public var algorithm: Algorithm+ /// Base64 of the signer's public key.+ public var publicKey: String+ /// Base64 of the detached signature over the artifact bytes.+ public var signature: String++ public init(algorithm: Algorithm = .ed25519, publicKey: String, signature: String) {+ self.algorithm = algorithm+ self.publicKey = publicKey+ self.signature = signature+ }+}diff --git a/apps/Donkey/Sources/DonkeyHarness/SkillSource.swift b/apps/Donkey/Sources/DonkeyHarness/SkillSource.swiftnew file mode 100644index 00000000..55d8a8ca--- /dev/null+++ b/apps/Donkey/Sources/DonkeyHarness/SkillSource.swift@@ -0,0 +1,67 @@+import Foundation++/// A reference to a skill the user wants to install, independent of where it lives. Today the only+/// concrete source reads bundles already on disk; the same ref shape is what a future catalog client+/// resolves over the network.+public struct SkillRef: Equatable, Sendable {+ public var skillID: String+ public var version: String?+ /// Source-specific locator (a file path for the local source; a catalog id/URL later).+ public var locator: String++ public init(skillID: String, version: String? = nil, locator: String) {+ self.skillID = skillID+ self.version = version+ self.locator = locator+ }+}++/// A skill bundle that a source has produced locally and is ready for the installer to verify and+/// place into the install directory. `url` points at either a directory or a `.zip` containing the+/// bundle (`SKILL.md`, optional `scripts/`, optional `manifest.json`).+public struct FetchedSkill: Equatable, Sendable {+ public var ref: SkillRef+ public var url: URL+ /// Manifest parsed from the bundle, when present. Carries the expected checksum/signature.+ public var manifest: HarnessSkillManifest?++ public init(ref: SkillRef, url: URL, manifest: HarnessSkillManifest? = nil) {+ self.ref = ref+ self.url = url+ self.manifest = manifest+ }+}++public enum SkillSourceError: Error, CustomStringConvertible, Equatable, Sendable {+ case notFound(String)+ case notImplemented(String)+ case malformedBundle(String)++ public var description: String {+ switch self {+ case .notFound(let message): return "Skill not found: \(message)"+ case .notImplemented(let message): return "Skill source not implemented: \(message)"+ case .malformedBundle(let message): return "Malformed skill bundle: \(message)"+ }+ }+}++/// Where installable skills come from. The installer depends only on this protocol, so the on-disk+/// "already downloaded" source and the future hosted-catalog client are interchangeable.+public protocol SkillSource: Sendable {+ func fetch(_ ref: SkillRef) async throws -> FetchedSkill+}++/// The seam the future site catalog drops into: it will resolve a `SkillRef` against+/// `DONKEY_WEB_BASE_URL`, download the bundle, and hand it to the installer for verification. The+/// download/publish API is not designed yet, so this is a deliberate stub — skills are treated as+/// "already downloaded" via `LocalDirectorySkillSource` for now.+public struct RemoteCatalogSkillSource: SkillSource {+ public init() {}++ public func fetch(_ ref: SkillRef) async throws -> FetchedSkill {+ throw SkillSourceError.notImplemented(+ "Remote skill catalog download is not wired yet; install from a local bundle for now."+ )+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/HarnessSkillInstallManager.swift b/apps/Donkey/Sources/DonkeyRuntime/HarnessSkillInstallManager.swiftnew file mode 100644index 00000000..5450a48e--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/HarnessSkillInstallManager.swift@@ -0,0 +1,56 @@+import DonkeyHarness+import Foundation++public extension Notification.Name {+ /// Posted after a skill is installed, updated, or uninstalled so observers (e.g. UI) can refresh.+ /// The harness itself does not need this — it re-reads the skill catalog at the start of each+ /// turn — but invalidating the discovery cache here makes a change visible immediately.+ static let donkeySkillsChanged = Notification.Name("com.donkey.skillsChanged")+}++/// Coordinates the install pipeline end to end: resolve a skill from a `SkillSource`, verify and+/// place it via `HarnessSkillInstaller`, then make it visible to the running harness.+///+/// Installed skills become live without any registry plumbing here: every consumer+/// (`app_skill`/`skill_run`, the planner's skill catalog, the per-run skill registry) reads+/// `BuiltInLocalAppSkillPacks.descriptors()`, which now folds in the installed directory. This+/// manager just performs the disk change, drops the discovery cache so the next read is fresh, and+/// announces it.+public struct HarnessSkillInstallManager: Sendable {+ public var source: SkillSource+ public var installer: HarnessSkillInstaller++ public init(+ source: SkillSource = LocalDirectorySkillSource(),+ installer: HarnessSkillInstaller = HarnessSkillInstaller()+ ) {+ self.source = source+ self.installer = installer+ }++ /// Install (or update — the layout is versioned, so installing a new version is the update) the+ /// referenced skill. Throws without changing the live install on any fetch/verify failure.+ @discardableResult+ public func install(_ ref: SkillRef) async throws -> HarnessSkillInstaller.InstallResult {+ let fetched = try await source.fetch(ref)+ let result = try installer.install(fetched)+ await refreshAfterChange()+ return result+ }++ public func uninstall(skillID: String) async throws {+ try installer.uninstall(skillID: skillID)+ await refreshAfterChange()+ }++ public func installedSkills() -> [InstallReceipt] {+ installer.installedReceipts()+ }++ private func refreshAfterChange() async {+ BuiltInLocalAppSkillPacks.invalidateInstalledCache()+ await MainActor.run {+ NotificationCenter.default.post(name: .donkeySkillsChanged, object: nil)+ }+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/HarnessSkillInstaller.swift b/apps/Donkey/Sources/DonkeyRuntime/HarnessSkillInstaller.swiftnew file mode 100644index 00000000..4d8a58b0--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/HarnessSkillInstaller.swift@@ -0,0 +1,408 @@+import CryptoKit+import DonkeyHarness+import Foundation++/// Installs verified skill bundles into the on-disk install directory and removes them again.+///+/// The pipeline is: materialize the fetched bundle into a temp working copy, verify its integrity+/// (content checksum + optional signature) BEFORE it touches the live install tree, then place it at+/// a versioned path and repoint the `current` symlink. Any failure throws and leaves the previously+/// installed version untouched — a bad download can never replace a good install.+///+/// Layout (under `Skills/Installed/`):+/// ```+/// <skillID>/<version>/{SKILL.md, scripts/, manifest.json, receipt.json}+/// <skillID>/current -> <version>+/// ```+public struct HarnessSkillInstaller: Sendable {+ public var installRoot: URL+ /// Base64 public keys whose signatures the host trusts. A signed bundle installs only when its+ /// signing key is in this set; an empty set rejects all signed bundles.+ public var trustedPublicKeys: Set<String>+ /// When true, a bundle without a verified signature is rejected. Off by default so locally+ /// authored / already-downloaded dev bundles install on checksum alone.+ public var requireSignature: Bool++ public init(+ installRoot: URL = HarnessSkillInstaller.defaultInstallRoot(),+ trustedPublicKeys: Set<String> = [],+ requireSignature: Bool = false+ ) {+ self.installRoot = installRoot+ self.trustedPublicKeys = trustedPublicKeys+ self.requireSignature = requireSignature+ }++ public static func defaultInstallRoot() -> URL {+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]+ .appendingPathComponent("Donkey", isDirectory: true)+ .appendingPathComponent("Skills", isDirectory: true)+ .appendingPathComponent("Installed", isDirectory: true)+ }++ public enum InstallError: Error, CustomStringConvertible, Equatable, Sendable {+ case missingSkillMarkdown+ case checksumMismatch(expected: String, actual: String)+ case untrustedSignature+ case invalidSignature+ case signatureRequired+ case extractionFailed(String)++ public var description: String {+ switch self {+ case .missingSkillMarkdown:+ return "Skill bundle has no SKILL.md."+ case .checksumMismatch(let expected, let actual):+ return "Skill checksum mismatch (expected \(expected), got \(actual))."+ case .untrustedSignature:+ return "Skill is signed by a key that is not trusted."+ case .invalidSignature:+ return "Skill signature does not verify."+ case .signatureRequired:+ return "Skill is unsigned but a signature is required."+ case .extractionFailed(let message):+ return "Could not extract skill bundle: \(message)"+ }+ }+ }++ public struct InstallResult: Equatable, Sendable {+ public var skillID: String+ public var version: String+ public var installedPath: URL+ public var verifiedChecksum: String+ public var signed: Bool+ }++ // MARK: - Install++ @discardableResult+ public func install(_ fetched: FetchedSkill) throws -> InstallResult {+ let fileManager = FileManager.default+ let staging = fileManager.temporaryDirectory+ .appendingPathComponent("donkey-skill-install-\(UUID().uuidString)", isDirectory: true)+ defer { try? fileManager.removeItem(at: staging) }++ let bundle = try materialize(fetched.url, into: staging)++ let skillMarkdown = bundle.appendingPathComponent("SKILL.md")+ guard fileManager.fileExists(atPath: skillMarkdown.path) else {+ throw InstallError.missingSkillMarkdown+ }++ let manifest = fetched.manifest+ ?? HarnessSkillManifest.load(from: bundle.appendingPathComponent(HarnessSkillManifest.fileName))+ let skillID = resolveSkillID(manifest: manifest, bundle: bundle, ref: fetched.ref)+ let version = manifest?.version ?? fetched.ref.version ?? "0.0.0"++ let checksum = Self.contentChecksum(of: bundle)+ if let expected = manifest?.checksum, expected.lowercased() != checksum {+ throw InstallError.checksumMismatch(expected: expected.lowercased(), actual: checksum)+ }++ let signed = try verifySignature(manifest?.signature, contentChecksumHex: checksum)+ if requireSignature && !signed {+ throw InstallError.signatureRequired+ }++ let skillRoot = installRoot.appendingPathComponent(skillID, isDirectory: true)+ let versionDir = skillRoot.appendingPathComponent(version, isDirectory: true)+ try fileManager.createDirectory(at: skillRoot, withIntermediateDirectories: true)++ // Swap the verified bundle into place. Build at a temp sibling, then rename, so a partially+ // written version directory is never observable.+ let incoming = skillRoot.appendingPathComponent(".incoming-\(UUID().uuidString)", isDirectory: true)+ if fileManager.fileExists(atPath: incoming.path) {+ try fileManager.removeItem(at: incoming)+ }+ try fileManager.copyItem(at: bundle, to: incoming)++ let receipt = InstallReceipt(+ skillID: skillID,+ version: version,+ installedAt: Date(),+ checksum: checksum,+ signed: signed,+ publicKey: signed ? manifest?.signature?.publicKey : nil,+ sourceLocator: fetched.ref.locator+ )+ try receipt.write(to: incoming.appendingPathComponent(InstallReceipt.fileName))++ if fileManager.fileExists(atPath: versionDir.path) {+ try fileManager.removeItem(at: versionDir)+ }+ try fileManager.moveItem(at: incoming, to: versionDir)++ try repointCurrent(skillRoot: skillRoot, to: version)++ return InstallResult(+ skillID: skillID,+ version: version,+ installedPath: versionDir,+ verifiedChecksum: checksum,+ signed: signed+ )+ }++ // MARK: - Uninstall++ public func uninstall(skillID: String) throws {+ let dir = installRoot.appendingPathComponent(skillID, isDirectory: true)+ if FileManager.default.fileExists(atPath: dir.path) {+ try FileManager.default.removeItem(at: dir)+ }+ }++ // MARK: - Listing++ public func installedReceipts() -> [InstallReceipt] {+ let fileManager = FileManager.default+ guard let entries = try? fileManager.contentsOfDirectory(+ at: installRoot,+ includingPropertiesForKeys: [.isDirectoryKey],+ options: [.skipsHiddenFiles]+ ) else {+ return []+ }+ return entries.compactMap { skillDir in+ let current = skillDir.appendingPathComponent("current", isDirectory: true)+ return InstallReceipt.load(from: current.appendingPathComponent(InstallReceipt.fileName))+ }+ .sorted { $0.skillID < $1.skillID }+ }++ /// The discovery root for installed skills: each `<skillID>/current` directory.+ public func currentBundleRoots() -> [URL] {+ let fileManager = FileManager.default+ guard let entries = try? fileManager.contentsOfDirectory(+ at: installRoot,+ includingPropertiesForKeys: [.isDirectoryKey],+ options: [.skipsHiddenFiles]+ ) else {+ return []+ }+ return entries+ .map { $0.appendingPathComponent("current", isDirectory: true) }+ .filter { fileManager.fileExists(atPath: $0.appendingPathComponent("SKILL.md").path) }+ }++ // MARK: - Internals++ private func materialize(_ source: URL, into staging: URL) throws -> URL {+ let fileManager = FileManager.default+ try fileManager.createDirectory(at: staging, withIntermediateDirectories: true)++ var isDirectory: ObjCBool = false+ guard fileManager.fileExists(atPath: source.path, isDirectory: &isDirectory) else {+ throw InstallError.extractionFailed("source does not exist at \(source.path)")+ }++ if isDirectory.boolValue {+ let dest = staging.appendingPathComponent("bundle", isDirectory: true)+ try fileManager.copyItem(at: source, to: dest)+ return Self.bundleRoot(in: dest)+ }++ // Treat a file as a zip archive and extract it with ditto (handles PKZip on macOS).+ let extracted = staging.appendingPathComponent("bundle", isDirectory: true)+ try fileManager.createDirectory(at: extracted, withIntermediateDirectories: true)+ try Self.unzip(source, to: extracted)+ return Self.bundleRoot(in: extracted)+ }++ /// A zip can wrap the bundle in a single top-level folder. If the extracted root contains exactly+ /// one directory and no SKILL.md, descend into it.+ private static func bundleRoot(in directory: URL) -> URL {+ let fileManager = FileManager.default+ if fileManager.fileExists(atPath: directory.appendingPathComponent("SKILL.md").path) {+ return directory+ }+ guard let entries = try? fileManager.contentsOfDirectory(+ at: directory,+ includingPropertiesForKeys: [.isDirectoryKey],+ options: [.skipsHiddenFiles]+ ) else {+ return directory+ }+ let directories = entries.filter { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true }+ if directories.count == 1,+ fileManager.fileExists(atPath: directories[0].appendingPathComponent("SKILL.md").path) {+ return directories[0]+ }+ return directory+ }++ private static func unzip(_ archive: URL, to destination: URL) throws {+ let process = Process()+ process.executableURL = URL(fileURLWithPath: "/usr/bin/ditto")+ process.arguments = ["-x", "-k", archive.path, destination.path]+ let pipe = Pipe()+ process.standardError = pipe+ do {+ try process.run()+ } catch {+ throw InstallError.extractionFailed(error.localizedDescription)+ }+ process.waitUntilExit()+ guard process.terminationStatus == 0 else {+ let message = String(+ data: pipe.fileHandleForReading.readDataToEndOfFile(),+ encoding: .utf8+ ) ?? "ditto exit \(process.terminationStatus)"+ throw InstallError.extractionFailed(message)+ }+ }++ private func resolveSkillID(+ manifest: HarnessSkillManifest?,+ bundle: URL,+ ref: SkillRef+ ) -> String {+ if let id = manifest?.skillID, !id.isEmpty { return id }+ if let id = Self.skillMarkdownID(at: bundle.appendingPathComponent("SKILL.md")) { return id }+ if !ref.skillID.isEmpty { return ref.skillID }+ return bundle.deletingLastPathComponent().lastPathComponent+ }++ /// Minimal `id:` frontmatter scan so an unmanifested bundle still installs under its declared id.+ private static func skillMarkdownID(at url: URL) -> String? {+ guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return nil }+ for line in contents.split(whereSeparator: \.isNewline).map(String.init).prefix(40) {+ let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)+ guard trimmed.lowercased().hasPrefix("id:") else { continue }+ let value = String(trimmed.dropFirst(3)).trimmingCharacters(in: .whitespacesAndNewlines)+ return value.isEmpty ? nil : value+ }+ return nil+ }++ /// Verifies the signature when present. Returns true if a valid, trusted signature was checked;+ /// false if there is no signature. Throws on a present-but-bad/untrusted signature.+ private func verifySignature(+ _ signature: HarnessSkillSignature?,+ contentChecksumHex: String+ ) throws -> Bool {+ guard let signature else { return false }+ guard trustedPublicKeys.contains(signature.publicKey) else {+ throw InstallError.untrustedSignature+ }+ guard+ let keyData = Data(base64Encoded: signature.publicKey),+ let sigData = Data(base64Encoded: signature.signature),+ let key = try? Curve25519.Signing.PublicKey(rawRepresentation: keyData)+ else {+ throw InstallError.invalidSignature+ }+ // The signature is over the canonical content digest bytes.+ let digest = Data(hexString: contentChecksumHex) ?? Data(contentChecksumHex.utf8)+ guard key.isValidSignature(sigData, for: digest) else {+ throw InstallError.invalidSignature+ }+ return true+ }++ private func repointCurrent(skillRoot: URL, to version: String) throws {+ let fileManager = FileManager.default+ let current = skillRoot.appendingPathComponent("current")+ // Remove any prior link/file regardless of type before recreating it.+ if (try? current.checkResourceIsReachable()) == true+ || (try? fileManager.attributesOfItem(atPath: current.path)) != nil {+ try? fileManager.removeItem(at: current)+ }+ // Relative destination ("<version>", not an absolute URL) so the link resolves next to+ // itself regardless of the install root's absolute path.+ try fileManager.createSymbolicLink(atPath: current.path, withDestinationPath: version)++ // Prune other versions so installs stay self-cleaning.+ if let versions = try? fileManager.contentsOfDirectory(+ at: skillRoot,+ includingPropertiesForKeys: [.isDirectoryKey],+ options: [.skipsHiddenFiles]+ ) {+ for entry in versions where entry.lastPathComponent != version && entry.lastPathComponent != "current" {+ if (try? entry.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true {+ try? fileManager.removeItem(at: entry)+ }+ }+ }+ }++ /// Packaging-independent content hash: SHA-256 over each file's relative path and bytes in sorted+ /// path order, excluding install/distribution metadata. The same value results whether the bundle+ /// arrived as a folder or a zip, so a manifest checksum is meaningful across both.+ public static func contentChecksum(of bundle: URL) -> String {+ let fileManager = FileManager.default+ let excluded: Set<String> = [HarnessSkillManifest.fileName, InstallReceipt.fileName]+ var files: [(relative: String, url: URL)] = []+ if let enumerator = fileManager.enumerator(+ at: bundle,+ includingPropertiesForKeys: [.isRegularFileKey],+ options: [.skipsHiddenFiles, .skipsPackageDescendants]+ ) {+ for case let url as URL in enumerator {+ guard (try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true else { continue }+ let relative = url.standardizedFileURL.path+ .replacingOccurrences(of: bundle.standardizedFileURL.path, with: "")+ .trimmingCharacters(in: CharacterSet(charactersIn: "/"))+ if excluded.contains((relative as NSString).lastPathComponent) { continue }+ files.append((relative, url))+ }+ }+ files.sort { $0.relative < $1.relative }++ var hasher = SHA256()+ for file in files {+ hasher.update(data: Data(file.relative.utf8))+ hasher.update(data: Data([0]))+ if let data = try? Data(contentsOf: file.url) {+ hasher.update(data: data)+ }+ }+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()+ }+}++/// What the installer records next to an installed skill. Read back to list installs and to know how+/// each was verified.+public struct InstallReceipt: Codable, Equatable, Sendable {+ public var skillID: String+ public var version: String+ public var installedAt: Date+ public var checksum: String+ public var signed: Bool+ public var publicKey: String?+ public var sourceLocator: String++ public static let fileName = "receipt.json"++ func write(to url: URL) throws {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]+ encoder.dateEncodingStrategy = .iso8601+ try encoder.encode(self).write(to: url, options: .atomic)+ }++ static func load(from url: URL) -> InstallReceipt? {+ guard let data = try? Data(contentsOf: url) else { return nil }+ let decoder = JSONDecoder()+ decoder.dateDecodingStrategy = .iso8601+ return try? decoder.decode(InstallReceipt.self, from: data)+ }+}++private extension Data {+ /// Parses an even-length lowercase/uppercase hex string into bytes; nil on malformed input.+ init?(hexString: String) {+ let chars = Array(hexString)+ guard chars.count % 2 == 0 else { return nil }+ var bytes = [UInt8]()+ bytes.reserveCapacity(chars.count / 2)+ var index = 0+ while index < chars.count {+ guard let byte = UInt8(String(chars[index ... index + 1]), radix: 16) else { return nil }+ bytes.append(byte)+ index += 2+ }+ self = Data(bytes)+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swiftindex 565ef8a1..43af3536 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swift@@ -22,7 +22,7 @@ public enum BuiltInLocalAppSkillPacks {/// mid-session, so unlike the bundled packs they are re-discovered with a short TTL. This is/// what makes learning compound: a pack saved in one session is matched and preloaded like a/// built-in in every later session.- private final class LearnedPackCache: @unchecked Sendable {+ private final class TTLDescriptorCache: @unchecked Sendable {private let lock = NSLock()private var cached: (descriptors: [HarnessSkillDescriptor], at: Date)?@@ -36,9 +36,16 @@ public enum BuiltInLocalAppSkillPacks {cached = (fresh, Date())return fresh}++ func invalidate() {+ lock.lock()+ defer { lock.unlock() }+ cached = nil+ }}- private static let learnedPackCache = LearnedPackCache()+ private static let learnedPackCache = TTLDescriptorCache()+ private static let installedPackCache = TTLDescriptorCache()public static func learnedDescriptors() -> [HarnessSkillDescriptor] {learnedPackCache.descriptors(ttl: 30) {@@ -49,9 +56,38 @@ public enum BuiltInLocalAppSkillPacks {}}- /// Bundled packs first so a curated built-in wins over a learned pack for the same app.+ /// Skills the user installed from the catalog. Each lives at `Installed/<id>/current`; like+ /// learned packs they can appear mid-session, so they are re-discovered with a short TTL.+ public static func installedDescriptors() -> [HarnessSkillDescriptor] {+ installedPackCache.descriptors(ttl: 30) {+ let roots = HarnessSkillInstaller().currentBundleRoots()+ guard !roots.isEmpty else { return [] }+ return HarnessSkillFileSystemSource(roots: roots, sourceKind: .installed).discover()+ }+ }++ /// Drop the installed-skill cache so a just-installed/uninstalled skill is visible immediately+ /// rather than after the TTL. Called by `HarnessSkillInstallManager` after a change.+ public static func invalidateInstalledCache() {+ installedPackCache.invalidate()+ }++ /// Built-in first, then installed, then learned, so a curated built-in always wins on an id+ /// collision and an installed catalog skill wins over a learned one. Dedup by id also guards the+ /// `HarnessSkillRegistry` (which keys uniquely on id) against a duplicate-id crash.public static func descriptors() -> [HarnessSkillDescriptor] {- cachedDescriptors + learnedDescriptors()+ dedupedByID(cachedDescriptors + installedDescriptors() + learnedDescriptors())+ }++ private static func dedupedByID(+ _ descriptors: [HarnessSkillDescriptor]+ ) -> [HarnessSkillDescriptor] {+ var seen = Set<String>()+ var result: [HarnessSkillDescriptor] = []+ for descriptor in descriptors where seen.insert(descriptor.id).inserted {+ result.append(descriptor)+ }+ return result}public static func instructionSnippet(diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalDirectorySkillSource.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalDirectorySkillSource.swiftnew file mode 100644index 00000000..01c160aa--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalDirectorySkillSource.swift@@ -0,0 +1,46 @@+import DonkeyHarness+import Foundation++/// Reads an "already downloaded" skill bundle from a path on disk and hands it to the installer.+///+/// This is the concrete `SkillSource` for now: distribution over the site catalog is not wired yet,+/// so a skill is whatever folder or `.zip` is already present locally. The locator on the `SkillRef`+/// is the bundle path; if it is omitted the source falls back to `<baseDirectory>/<skillID>`.+public struct LocalDirectorySkillSource: SkillSource {+ /// Optional directory the source resolves skill ids against when a ref carries no absolute path.+ public var baseDirectory: URL?++ public init(baseDirectory: URL? = nil) {+ self.baseDirectory = baseDirectory+ }++ public func fetch(_ ref: SkillRef) async throws -> FetchedSkill {+ let url = try resolve(ref)+ guard FileManager.default.fileExists(atPath: url.path) else {+ throw SkillSourceError.notFound(url.path)+ }+ let manifest = manifest(forBundleAt: url)+ return FetchedSkill(ref: ref, url: url, manifest: manifest)+ }++ private func resolve(_ ref: SkillRef) throws -> URL {+ if !ref.locator.isEmpty {+ return URL(fileURLWithPath: ref.locator)+ }+ guard let baseDirectory else {+ throw SkillSourceError.notFound("no locator and no base directory for \(ref.skillID)")+ }+ return baseDirectory.appendingPathComponent(ref.skillID, isDirectory: true)+ }++ /// Loads the manifest from a directory bundle so the installer can verify checksum/signature.+ /// Zip bundles are read after extraction by the installer, so nil here is fine.+ private func manifest(forBundleAt url: URL) -> HarnessSkillManifest? {+ var isDirectory: ObjCBool = false+ guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory),+ isDirectory.boolValue else {+ return nil+ }+ return HarnessSkillManifest.load(from: url.appendingPathComponent(HarnessSkillManifest.fileName))+ }+}