From 8c4d3bb55a0152beb50a39008e82bcda8780ce6a Mon Sep 17 00:00:00 2001 From: XiaoSeS <87064762+XiaoSeS@users.noreply.github.com> Date: Tue, 3 Nov 2026 20:13:56 +0800 Subject: [PATCH] feat(dsh): import and export local skill packages Signed-off-by: XiaoSeS <87064762+XiaoSeS@users.noreply.github.com> --- cli/src/integrations/install-recovery.ts | 4 +- cli/src/integrations/install-rollback.ts | 2 +- cli/src/integrations/local-skills.ts | 2 + cli/src/integrations/native-contract.d.ts | 3 + cli/src/integrations/native-install.ts | 10 +- cli/src/integrations/native-installed.ts | 2 +- cli/src/integrations/native-runtime.ts | 60 ++++++-- cli/src/integrations/operation-store.ts | 28 +++- cli/src/integrations/package-transfer.ts | 103 +++++++++++++ cli/src/integrations/transaction-journal.ts | 1 + cli/src/platform/archive.ts | 22 +++ cli/src/services/install-service.ts | 10 +- cli/src/services/installed-skill-metadata.ts | 2 +- .../fixtures/package-import-crash-child.ts | 27 ++++ .../unit/integrations/native-runtime.test.ts | 3 +- .../integrations/package-import-crash.test.ts | 35 +++++ .../integrations/package-transfer.test.ts | 114 ++++++++++++++ cli/test/unit/platform/archive.test.ts | 20 +++ .../package-transfer-design.md | 51 +++++++ .../changes/add-dsh-native-plugin/proposal.md | 1 + .../specs/dsh-skill-consumption/spec.md | 20 +++ .../changes/add-dsh-native-plugin/tasks.md | 9 ++ .../add-dsh-native-plugin/verification.md | 30 ++++ plugins/dsh/README.en.md | 8 + plugins/dsh/README.md | 8 + plugins/dsh/src/client/detail-content.tsx | 6 +- plugins/dsh/src/client/detail-tabs.tsx | 8 +- plugins/dsh/src/client/index.tsx | 4 + .../src/client/installed-card-metadata.tsx | 21 +++ plugins/dsh/src/client/installed-skills.tsx | 25 ++-- plugins/dsh/src/client/management-result.ts | 2 +- .../dsh/src/client/management-tool-view.tsx | 80 ++++++---- .../dsh/src/client/native-control-styles.tsx | 31 +++- plugins/dsh/src/client/package-transfer.tsx | 139 ++++++++++++++++++ plugins/dsh/src/host/index.ts | 126 +++++++++++++++- plugins/dsh/src/host/local-runtime.ts | 18 +++ plugins/dsh/src/host/types.ts | 5 +- .../dsh/test/detail-reading-render.test.tsx | 10 ++ plugins/dsh/test/management-view.test.tsx | 6 +- .../dsh/test/package-transfer-host.test.ts | 47 ++++++ plugins/dsh/test/package-transfer-ui.test.tsx | 61 ++++++++ plugins/dsh/test/package.test.ts | 6 +- plugins/dsh/test/runtime-execution.test.ts | 3 + 43 files changed, 1074 insertions(+), 99 deletions(-) create mode 100644 cli/src/integrations/package-transfer.ts create mode 100644 cli/test/fixtures/package-import-crash-child.ts create mode 100644 cli/test/unit/integrations/package-import-crash.test.ts create mode 100644 cli/test/unit/integrations/package-transfer.test.ts create mode 100644 openspec/changes/add-dsh-native-plugin/package-transfer-design.md create mode 100644 plugins/dsh/src/client/installed-card-metadata.tsx create mode 100644 plugins/dsh/src/client/package-transfer.tsx create mode 100644 plugins/dsh/test/package-transfer-host.test.ts create mode 100644 plugins/dsh/test/package-transfer-ui.test.tsx diff --git a/cli/src/integrations/install-recovery.ts b/cli/src/integrations/install-recovery.ts index 56bc30217..c0c804b83 100644 --- a/cli/src/integrations/install-recovery.ts +++ b/cli/src/integrations/install-recovery.ts @@ -134,7 +134,7 @@ async function inspectInstallation(options: InstallRecoveryOptions, mode: 'inspe const metadata = read.metadata if (!sameInstalledSkillSource(metadata, identity) || metadata.version !== target.version || metadata.fingerprint !== target.fingerprint || metadata.agent !== target.agent - || metadata.installedAt !== target.installedAt || metadata.source !== 'skillhub') { + || metadata.installedAt !== target.installedAt || metadata.source !== (identity.registry === 'local:import' ? 'local-import' : 'skillhub')) { return result('unknown', 'metadata-conflict') } const snapshot = await snapshotInstalledSkillDirectory(item, target) @@ -265,7 +265,7 @@ async function assertBackupContent(stateDirectory: string, record: OperationReco const metadata = read.metadata if (!sameInstalledSkillSource(metadata, identity) || metadata.version !== target.version || metadata.fingerprint !== target.fingerprint || metadata.installedAt !== target.installedAt - || metadata.agent !== target.agent || metadata.source !== 'skillhub') throw new Error('Backup metadata does not match its baseline') + || metadata.agent !== target.agent || metadata.source !== (identity.registry === 'local:import' ? 'local-import' : 'skillhub')) throw new Error('Backup metadata does not match its baseline') const snapshot = await snapshotJournalInstallation(record, path) if (snapshot.fingerprint !== target.fingerprint || !isDeepStrictEqual(snapshot.files, metadata.files)) { const proof = JSON.parse(await readFile(join(dirname(stateDirectory), 'dirty-upgrade-proofs', `${record.operationId}.json`), 'utf8')) as { diff --git a/cli/src/integrations/install-rollback.ts b/cli/src/integrations/install-rollback.ts index e71f9dd80..b3d413f53 100644 --- a/cli/src/integrations/install-rollback.ts +++ b/cli/src/integrations/install-rollback.ts @@ -142,7 +142,7 @@ async function assertContent(record: OperationRecord, path: string, expected: In const read = await readInstalledSkillMetadata(path) if (read.status !== 'valid') throw new Error('Recovery metadata is unavailable') const value = read.metadata - if (!sameInstalledSkillSource(value, expected) || value.source !== 'skillhub' || value.version !== expected.version + if (!sameInstalledSkillSource(value, expected) || value.source !== (expected.registry === 'local:import' ? 'local-import' : 'skillhub') || value.version !== expected.version || value.fingerprint !== expected.fingerprint || value.agent !== expected.agent || value.installedAt !== expected.installedAt) throw new Error('Recovery identity changed') const snapshot = await snapshotJournalInstallation(record, path) if (snapshot.fingerprint !== expected.fingerprint || !isDeepStrictEqual(snapshot.files, value.files)) throw new Error('Recovery content changed') diff --git a/cli/src/integrations/local-skills.ts b/cli/src/integrations/local-skills.ts index dbf680dbd..648ed2f11 100644 --- a/cli/src/integrations/local-skills.ts +++ b/cli/src/integrations/local-skills.ts @@ -30,3 +30,5 @@ export { inspectRemovalBaseline } from './removal-baseline' export { parseSkillExamples, readSkillExamples } from '../services/skill-examples' export type { SkillExample, SkillExamples } from '../services/skill-examples' + +export { previewPackage, exportPackage, LOCAL_PACKAGE_REGISTRY, MAX_TRANSFER_BYTES } from './package-transfer' diff --git a/cli/src/integrations/native-contract.d.ts b/cli/src/integrations/native-contract.d.ts index f08c052e1..78b890c8e 100644 --- a/cli/src/integrations/native-contract.d.ts +++ b/cli/src/integrations/native-contract.d.ts @@ -92,6 +92,9 @@ export interface NativeFileResetExecution { authorize: NativeRemovalExecution['authorize'] } export interface NativeRuntime { + previewPackage(archive: Uint8Array, validate: (directory: string) => Promise<{name: string; summary?: string}>): Promise<{name: string; summary?: string; files: number; bytes: number; fingerprint: string}> + exportPackage(selected: UpgradeSelection, target: InstalledProjectionTarget): Promise<{filename: string; archive: Uint8Array}> + executePackageImport(request: NativeInstallExecution & {archive: Uint8Array}): Promise inspectChanges(selected: UpgradeSelection, target: InstalledProjectionTarget): Promise readChangeDiff(snapshot: Extract | VersionChangesSnapshot, path: string): Promise prepareVersionChanges(selected: UpgradeSelection, target: InstalledProjectionTarget, diff --git a/cli/src/integrations/native-install.ts b/cli/src/integrations/native-install.ts index dc97d7cf5..2df3fb8c7 100644 --- a/cli/src/integrations/native-install.ts +++ b/cli/src/integrations/native-install.ts @@ -10,7 +10,7 @@ import { createInstallTransactionObserver } from './transaction-journal' import { confirmExistingNativeInstall } from './native-installed' /** Claim an accepted operation exactly once before performing network or target writes. */ -export async function executeNativeInstall(operations: OperationStore, inventory: InventoryStore, request: NativeInstallExecution): Promise { +export async function executeNativeInstall(operations: OperationStore, inventory: InventoryStore, request: NativeInstallExecution & { archive?: Uint8Array }): Promise { request = { ...request } const record = await operations.get(request.operationId, request.ownerId) if (!record || record.operation.kind !== 'install' || record.operation.status.phase !== 'accepted') throw new Error('Installation is not owned and accepted') @@ -28,16 +28,18 @@ export async function executeNativeInstall(operations: OperationStore, inventory try { if (await canonicalizeExistingPath(root) !== root) throw new Error('Installation target changed') await request.authorize([root, target], 'staging') - const existing = await confirmExistingNativeInstall(operations, inventory, request) + const existing = request.registry === 'local:import' ? undefined : await confirmExistingNativeInstall(operations, inventory, request) if (existing) return existing const client = new SkillHubClient(request.registry) - const resolved = await client.resolve(request.namespace, request.slug, request.version) + const imported = request.registry === 'local:import' + if (imported !== !!request.archive || imported && (request.namespace !== 'local' || request.version !== 'local')) throw new Error('Invalid local package source') + const resolved = imported ? { namespace: request.namespace, slug: request.slug, version: request.version, versionId: 1, fingerprint: request.fingerprint, downloadUrl: '' } : await client.resolve(request.namespace, request.slug, request.version) if (resolved.namespace !== request.namespace || resolved.slug !== request.slug || resolved.version !== request.version || resolved.versionId !== request.versionId || resolved.fingerprint !== request.fingerprint) throw new Error('Installation release changed') const observer = await createInstallTransactionObserver(operations, record.operationId, record.ownerId) coreStarted = true await installSkill({ registry: request.registry, namespace: request.namespace, slug: request.slug, - version: request.version, resolved, client, force: false, inventoryStore: inventory, + version: request.version, resolved, client, ...(imported ? {packageBytes: request.archive, metadataSource: 'local-import' as const} : {}), force: false, inventoryStore: inventory, targets: [{ agent: 'dsh', rootDir: root, scope: request.scope, source: 'explicit' }], transactionObserver: observer, authorizeTargetMutation: request.authorize, validateStagedSkill: request.validateStaged }) const result = await reconcileCommittedInstallation({ operations, inventory, diff --git a/cli/src/integrations/native-installed.ts b/cli/src/integrations/native-installed.ts index 15fbefc1f..a07aed7f9 100644 --- a/cli/src/integrations/native-installed.ts +++ b/cli/src/integrations/native-installed.ts @@ -57,7 +57,7 @@ export async function verifyExistingInstallation(current: Inventory, if (metadata.status !== 'valid' || !sameInstalledSkillSource(metadata.metadata, request) || metadata.metadata.version !== request.version || metadata.metadata.versionId !== request.versionId || metadata.metadata.fingerprint !== request.fingerprint || metadata.metadata.agent !== 'dsh' - || metadata.metadata.installedAt !== owner.entry.installedAt || metadata.metadata.source !== 'skillhub') throw new Error('Existing installation metadata does not match') + || metadata.metadata.installedAt !== owner.entry.installedAt || metadata.metadata.source !== (request.registry === 'local:import' ? 'local-import' : 'skillhub')) throw new Error('Existing installation metadata does not match') const snapshot = await snapshotSkillDirectory(target) if (snapshot.fingerprint !== request.fingerprint || !isDeepStrictEqual(snapshot.files, metadata.metadata.files)) throw new Error('Existing installation has local changes') return { fingerprint: request.fingerprint, versionId: request.versionId, diff --git a/cli/src/integrations/native-runtime.ts b/cli/src/integrations/native-runtime.ts index a22948da4..f38635367 100644 --- a/cli/src/integrations/native-runtime.ts +++ b/cli/src/integrations/native-runtime.ts @@ -1,8 +1,10 @@ +import { previewPackage, exportPackage, LOCAL_PACKAGE_REGISTRY } from './package-transfer' import { FileResetStore } from './native-file-reset' import { backupChanges, inspectChanges, prepareVersionChanges, readChangeDiff } from './native-changes' import { createHash } from 'node:crypto' import { readFile } from 'node:fs/promises' import { join } from 'node:path' +import { canonicalizeExistingPath, pathsOverlap } from '../platform/paths' import { isDeepStrictEqual } from 'node:util' import { inspectToggle, executeNativeToggle, recoverToggle } from './native-toggle' import { readSkillExamples } from '../services/skill-examples' @@ -26,6 +28,8 @@ import { acquireSkillTargetLock } from '../services/skill-target-lock' export async function openNativeRuntime(options: { stateDirectory: string; inventoryHome: string }): Promise { const operations = await OperationStore.open(options.stateDirectory) const inventory = new InventoryStore(options.inventoryHome) + const imports = new InventoryStore(join(options.stateDirectory, 'local-imports')) + const storeFor = (registry: string) => registry === LOCAL_PACKAGE_REGISTRY ? imports : inventory const resets = new FileResetStore(options.stateDirectory, operations.hostInstanceId, inventory, async () => { if ((await operations.listForRecovery()).length) throw new Error('Operation recovery required') }) @@ -36,8 +40,30 @@ export async function openNativeRuntime(options: { stateDirectory: string; inven if ((await resets.list()).some(record => !['completed', 'failed'].includes(record.operation.phase))) throw new Error('File reset recovery required') await inventory.ensureWritable() } + const guardForeignClaims = (request: import('./native-contract').NativeInstallExecution, foreign: InventoryStore): typeof request.authorize => async (paths, phase) => { + await request.authorize(paths, phase) + if (phase !== 'staging' && phase !== 'replace') return + // Replacement callbacks run under the same target lock used by both sources. + // A missing directory does not erase a persisted ownership claim. + const destination = join(request.root, request.slug) + const state = await foreign.read() + const claims = [...state.items.flatMap(item => item.targets.map(target => target.installDir)), + ...(state.suites ?? []).flatMap(suite => suite.members.flatMap(member => member.installDirs))] + for (const claim of claims) { + if (pathsOverlap(await canonicalizeExistingPath(claim), destination)) throw new Error('Import conflicts with a Registry installation record or local installation record') + } + } const runtime: NativeRuntime = { hostInstanceId: operations.hostInstanceId, + previewPackage, + exportPackage: (selected, target) => exportPackage(storeFor(selected.registry), selected, target), + executePackageImport: async request => { + if (request.registry !== LOCAL_PACKAGE_REGISTRY || request.namespace !== 'local' || request.version !== 'local') throw new Error('Invalid import identity') + await ensureCompatible() + await imports.ensureWritable() + const authorize = guardForeignClaims(request, inventory) + return withOperationLease(operations, request.operationId, request.ownerId, () => executeNativeInstall(operations, imports, {...request, authorize})) + }, inspectChanges: (selected, target) => inspectChanges(inventory, selected, target), readChangeDiff: (snapshot, path) => readChangeDiff(options.stateDirectory, inventory, snapshot, path), prepareVersionChanges: (selected, target, candidate) => prepareVersionChanges(options.stateDirectory, inventory, selected, target, candidate), @@ -51,15 +77,15 @@ export async function openNativeRuntime(options: { stateDirectory: string; inven }, executeFileReset: request => resets.execute(request), readInstallationEntry: async (selected, target) => { - const baseline = await inspectUpgradeBaseline(inventory, { ...selected }, [{ ...target }]) + const baseline = await inspectUpgradeBaseline(storeFor(selected.registry), { ...selected }, [{ ...target }], selected.registry === LOCAL_PACKAGE_REGISTRY) if (baseline.status !== 'ready' || baseline.targets.length !== 1) return undefined const entry = baseline.inventoryItem.targets[0]! const content = await readFile(join(entry.installDir, entry.installationState === 'disabled' ? 'SKILL.md.disabled' : 'SKILL.md')) if (createHash('sha256').update(content).digest('hex') !== baseline.targets[0]!.files['SKILL.md'] - || !isDeepStrictEqual(baseline, await inspectUpgradeBaseline(inventory, { ...selected }, [{ ...target }]))) return undefined + || !isDeepStrictEqual(baseline, await inspectUpgradeBaseline(storeFor(selected.registry), { ...selected }, [{ ...target }], selected.registry === LOCAL_PACKAGE_REGISTRY))) return undefined return content.toString('utf8') }, - inspectToggle: (selected, target, desiredState) => inspectToggle(inventory, { ...selected }, { ...target }, desiredState), + inspectToggle: (selected, target, desiredState) => inspectToggle(storeFor(selected.registry), { ...selected }, { ...target }, desiredState), acceptToggle: async (request, validateNew) => { const result = await operations.accept({ hostInstanceId: request.hostInstanceId, ownerId: request.ownerId, requestKey: request.requestKey, mode: request.mode, requestDigest: operationRequestDigest({ ...request.parameters, kind: 'toggle' }) }, @@ -75,12 +101,13 @@ export async function openNativeRuntime(options: { stateDirectory: string; inven await ensureCompatible() const snapshot = { ...request, baseline: structuredClone(request.baseline) } return withOperationLease(operations, snapshot.operationId, snapshot.ownerId, - () => executeNativeToggle(operations, inventory, snapshot)) + () => executeNativeToggle(operations, storeFor(snapshot.baseline.inventoryItem.registry), snapshot)) }, readSkillExamples, - observeInstallation: (operationId, ownerId, trustedRoots, observe) => observeInstallationDiscovery({ - operations, inventory, operationId, ownerId, trustedRoots, observe - }), + observeInstallation: async (operationId, ownerId, trustedRoots, observe) => { + const record = await operations.get(operationId, ownerId) + return observeInstallationDiscovery({operations, inventory: storeFor(record?.operation.context.sourceIdentity ?? ''), operationId, ownerId, trustedRoots, observe}) + }, findPlanOperation: async request => { const reset = (await resets.list()).find(record => record.ownerId === request.ownerId && record.requestKey === request.requestKey) if (reset) { @@ -112,7 +139,7 @@ export async function openNativeRuntime(options: { stateDirectory: string; inven await ensureCompatible() const snapshot = { ...request, baseline: structuredClone(request.baseline) } return withOperationLease(operations, snapshot.operationId, snapshot.ownerId, - () => executeNativeRemoval(operations, inventory, snapshot)) + () => executeNativeRemoval(operations, storeFor(snapshot.baseline.inventoryItem.registry), snapshot)) }, acceptRemoval: async (request, validateNew) => { const result = await operations.accept({ hostInstanceId: request.hostInstanceId, ownerId: request.ownerId, @@ -125,8 +152,9 @@ export async function openNativeRuntime(options: { stateDirectory: string; inven }) return result ? projectOperation(result) : undefined }, - inspectRemoval: (selected, target) => inspectRemovalBaseline(inventory, { ...selected }, { ...target }), + inspectRemoval: (selected, target) => inspectRemovalBaseline(storeFor(selected.registry), { ...selected }, { ...target }), executeUpgrade: async request => { + if (request.baseline.inventoryItem.registry === LOCAL_PACKAGE_REGISTRY) throw new Error('Local packages cannot be upgraded') await ensureCompatible() const snapshot = { ...request, baseline: structuredClone(request.baseline), ...(request.localChangesAuthorization ? { localChangesAuthorization: structuredClone(request.localChangesAuthorization) } : {}) } return withOperationLease(operations, snapshot.operationId, snapshot.ownerId, @@ -139,15 +167,18 @@ export async function openNativeRuntime(options: { stateDirectory: string; inven return result ? projectOperation(result) : undefined }, assessUpdate: assessSkillUpdate, - inspectUpgrade: (selected, targets) => inspectUpgradeBaseline(inventory, { ...selected }, targets.map(target => ({ ...target }))), + inspectUpgrade: (selected, targets) => inspectUpgradeBaseline(storeFor(selected.registry), { ...selected }, targets.map(target => ({ ...target }))), openInstalledSnapshot: (registry, targets) => openInstalledProjectionSnapshot(inventory, registry, targets), - listAllInstalled: targets => readAllInstalledProjection(inventory, targets.map(target => ({ ...target }))), + listAllInstalled: async targets => { + const results = await Promise.all([inventory, imports].map(store => readAllInstalledProjection(store, targets.map(target => ({ ...target }))))) + return {items: results.flatMap(result => result.items), complete: results.every(result => result.complete), issues: [...new Set(results.flatMap(result => result.issues))]} + }, listInstalled: (registry, targets) => readInstalledProjection(inventory, registry, targets.map(target => ({ ...target }))), executeInstall: async request => { await ensureCompatible() const snapshot = { ...request } return withOperationLease(operations, snapshot.operationId, snapshot.ownerId, - () => executeNativeInstall(operations, inventory, snapshot)) + () => executeNativeInstall(operations, inventory, {...snapshot, authorize: guardForeignClaims(snapshot, imports)})) }, acceptInstall: async (request, validateNew) => { const result = await operations.accept({ hostInstanceId: request.hostInstanceId, ownerId: request.ownerId, @@ -171,8 +202,9 @@ export async function openNativeRuntime(options: { stateDirectory: string; inven const paths = [...trustedTargetPaths] const result = await withOperationLease(operations, operationId, ownerId, async () => { const record = await operations.get(operationId, ownerId) - const input = { operations, inventory, operationId, ownerId, trustedTargetPaths: paths, authorizeMutation: authorize } - if (record && ['enable', 'disable'].includes(record.operation.kind)) return recoverToggle(operations, inventory, operationId, ownerId, paths, authorize) + const selectedStore = storeFor(record?.operation.context.sourceIdentity ?? '') + const input = { operations, inventory: selectedStore, operationId, ownerId, trustedTargetPaths: paths, authorizeMutation: authorize } + if (record && ['enable', 'disable'].includes(record.operation.kind)) return recoverToggle(operations, selectedStore, operationId, ownerId, paths, authorize) return record && ['uninstall', 'remove-stale-record'].includes(record.operation.kind) ? recoverRemoval(input) : recoverInstallation(input) }) diff --git a/cli/src/integrations/operation-store.ts b/cli/src/integrations/operation-store.ts index 4fecab694..ab72863e4 100644 --- a/cli/src/integrations/operation-store.ts +++ b/cli/src/integrations/operation-store.ts @@ -82,12 +82,12 @@ export class OperationStore { // Validation must not run under the journal lock: lifecycle code acquires target locks first. const accepted = input.parse(await validateNew()) const source = new URL(accepted.context.sourceIdentity) - if (!['http:', 'https:'].includes(source.protocol) || source.username || source.password || source.search || source.hash) throw new Error('Unsafe source identity') + if (!(accepted.context.sourceIdentity === 'local:import' && accepted.namespace === 'local' && accepted.version === 'local') && (!['http:', 'https:'].includes(source.protocol) || source.username || source.password || source.search || source.hash)) throw new Error('Unsafe source identity') return this.locked(async () => { const duplicate = await this.findRequest(request) if (duplicate) return duplicate const now = new Date().toISOString() - const value: OperationRecord = { schemaVersion: ['enable', 'disable'].includes(accepted.kind) ? 3 : 2, operationId: randomUUID(), ownerId: request.ownerId, + const value: OperationRecord = { schemaVersion: accepted.context.sourceIdentity === 'local:import' || ['enable', 'disable'].includes(accepted.kind) ? 3 : 2, operationId: randomUUID(), ownerId: request.ownerId, requestKey: request.requestKey, requestDigest: request.requestDigest, revision: 0, operation: { ...accepted, context: { ...accepted.context, hostInstanceId: this.hostInstanceId, createdAt: now, updatedAt: now }, status: { phase: 'accepted', files: 'pending', discovery: 'unconfirmed', recovery: 'not-needed', warnings: [] } } } @@ -394,10 +394,13 @@ export class OperationStore { private path(operationId: string): string { return join(this.root, `${id.parse(operationId)}.json`) } private async read(operationId: string): Promise { await this.validateExtendedDirectory() + await this.validateExtendedDirectory('local-packages') + const local = await readJson(this.localPackagePath(operationId)) const extended = await readJson(this.extendedPath(operationId)) const ordinary = await readJson(this.path(operationId)) if (extended !== undefined && ordinary !== undefined && !isDeepStrictEqual(extended, ordinary)) throw new OperationStoreError('CORRUPT_RECORD') - const json = extended ?? ordinary + if (local !== undefined && [extended, ordinary].some(value => value !== undefined && !isDeepStrictEqual(local, value))) throw new OperationStoreError('CORRUPT_RECORD') + const json = local ?? extended ?? ordinary if (json === undefined) return undefined const parsed = record.safeParse(json) if (!parsed.success || parsed.data.operationId !== operationId || parsed.data.operation.context.hostInstanceId !== this.hostInstanceId) throw new OperationStoreError('CORRUPT_RECORD') @@ -419,7 +422,9 @@ export class OperationStore { const values: OperationRecord[] = [] await this.validateExtendedDirectory() const extended = await readdir(join(this.root, 'activation')).catch((error: NodeJS.ErrnoException) => { if (error.code === 'ENOENT') return []; throw error }) - for (const name of [...new Set([...(await readdir(this.root)), ...extended])].sort()) { + await this.validateExtendedDirectory('local-packages') + const local = await readdir(join(this.root, 'local-packages')).catch((error: NodeJS.ErrnoException) => { if (error.code === 'ENOENT') return []; throw error }) + for (const name of [...new Set([...(await readdir(this.root)), ...extended, ...local])].sort()) { if (name === 'host.json' || !name.endsWith('.json')) continue const value = await this.read(name.slice(0, -5)) if (!value) throw new OperationStoreError('CORRUPT_RECORD') @@ -430,15 +435,17 @@ export class OperationStore { private extendedPath(operationId: string): string { return join(this.root, 'activation', `${id.parse(operationId)}.json`) } - private async validateExtendedDirectory(): Promise { + private localPackagePath(operationId: string): string { return join(this.root, 'local-packages', `${id.parse(operationId)}.json`) } + + private async validateExtendedDirectory(directory = 'activation'): Promise { try { - const info = await lstat(join(this.root, 'activation')) + const info = await lstat(join(this.root, directory)) if (!info.isDirectory() || info.isSymbolicLink() || (process.getuid && info.uid !== process.getuid())) throw new OperationStoreError('CORRUPT_RECORD') } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error } } - private async prepareExtendedDirectory(): Promise { - const path = join(this.root, 'activation') + private async prepareExtendedDirectory(directory = 'activation'): Promise { + const path = join(this.root, directory) await mkdir(path, { recursive: true, mode: 0o700 }) const info = await lstat(path) if (!info.isDirectory() || info.isSymbolicLink() || (process.getuid && info.uid !== process.getuid())) throw new OperationStoreError('CORRUPT_RECORD') @@ -481,6 +488,11 @@ export class OperationStore { } private async writeRecord(value: OperationRecord): Promise { + if (value.operation.context.sourceIdentity === 'local:import') { + await this.prepareExtendedDirectory('local-packages') + await writeOperationRecord(this.localPackagePath(value.operationId), {...value, schemaVersion: 3}, this.replaceFile) + return + } const extended = value.schemaVersion === 3 || await readJson(this.extendedPath(value.operationId)) !== undefined || operationSnapshots(value).some(snapshot => snapshot.items.some(item => item.targets.some(target => target.installationState === 'disabled'))) if (extended) { await this.prepareExtendedDirectory() diff --git a/cli/src/integrations/package-transfer.ts b/cli/src/integrations/package-transfer.ts new file mode 100644 index 000000000..3f65a53c4 --- /dev/null +++ b/cli/src/integrations/package-transfer.ts @@ -0,0 +1,103 @@ +import { createHash } from 'node:crypto' +import { constants } from 'node:fs' +import { mkdtemp, rm, lstat, open, realpath, readdir } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { zipSync } from 'fflate' +import { extractZip, MAX_SINGLE_FILE_BYTES, MAX_ZIP_ENTRIES } from '../platform/archive' +import { MAX_PACKAGE_BYTES } from '../platform/download' +import { snapshotSkillDirectory } from '../services/skill-fingerprint' +import { snapshotInstalledSkillDirectory } from '../services/installed-skill-snapshot' +import { inspectUpgradeBaseline } from './upgrade-baseline' +import { acquireSkillTargetLock } from '../services/skill-target-lock' +import type { InventoryStore } from '../stores/inventory-store' +import type { UpgradeSelection, InstalledProjectionTarget } from './native-contract' + +export const LOCAL_PACKAGE_REGISTRY = 'local:import' +export const MAX_TRANSFER_BYTES = 8 * 1024 * 1024 +export interface PackageInspection { name: string; summary?: string; files: number; bytes: number; fingerprint: string } +export async function previewPackage(archive: Uint8Array, validate: (directory: string) => Promise<{name: string; summary?: string}>): Promise { + if (!archive.byteLength || archive.byteLength > MAX_TRANSFER_BYTES) throw new Error('Package exceeds transfer size limit') + const directory = await mkdtemp(join(tmpdir(), 'skillhub-package-')) + try { + await extractZip(archive.slice().buffer, directory, { rejectInternalMetadata: true }) + const entry = await lstat(join(directory, 'SKILL.md')) + if (!entry.isFile()) throw new Error('Package requires root SKILL.md') + try { await lstat(join(directory, 'SKILL.md.disabled')); throw new Error('Ambiguous package entry') } + catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error } + const declaration = await validate(directory) + if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(declaration.name) || declaration.name.length > 128) throw new Error('Invalid skill name') + const snapshot = await snapshotSkillDirectory(directory) + let bytes = 0 + for (const path of Object.keys(snapshot.files)) bytes += (await lstat(join(directory, path))).size + return { ...declaration, files: Object.keys(snapshot.files).length, bytes, fingerprint: snapshot.fingerprint } + } finally { await rm(directory, { recursive: true, force: true }) } +} + +export async function exportPackage(inventory: InventoryStore, selected: UpgradeSelection, target: InstalledProjectionTarget): Promise<{filename: string; archive: Uint8Array}> { + const release = await acquireSkillTargetLock(target.root, selected.slug) + try { + await assertBoundedTree(join(target.root, selected.slug)) + const baseline = await inspectUpgradeBaseline(inventory, selected, [target], true) + if (baseline.status !== 'ready' || baseline.inventoryItem.targets.length !== 1) throw new Error('Installation cannot be exported') + const entry = baseline.inventoryItem.targets[0]! + const before = await snapshotInstalledSkillDirectory(baseline.inventoryItem, entry) + const paths = Object.keys(before.files) + if (paths.length > MAX_ZIP_ENTRIES) throw new Error('Too many package files') + const files: Record = {} + let total = 0 + for (const path of paths) { + const source = path === 'SKILL.md' && entry.installationState === 'disabled' ? 'SKILL.md.disabled' : path + const full = join(entry.installDir, source) + if (await realpath(full) !== full) throw new Error('Unsafe package file') + const stat = await lstat(full) + if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_SINGLE_FILE_BYTES) throw new Error('Unsafe package file') + total += stat.size + if (total > MAX_PACKAGE_BYTES) throw new Error('Package exceeds expanded size limit') + const handle = await open(full, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)) + try { + const opened = await handle.stat() + if (opened.ino !== stat.ino || opened.dev !== stat.dev || !opened.isFile()) throw new Error('Package changed') + const data = new Uint8Array(stat.size) + let offset = 0 + while (offset < data.length) { + const chunk = await handle.read(data, offset, data.length - offset, offset) + if (!chunk.bytesRead) throw new Error('Package changed') + offset += chunk.bytesRead + } + const afterRead = await handle.stat() + if (afterRead.size !== stat.size || afterRead.mtimeMs !== opened.mtimeMs || createHash('sha256').update(data).digest('hex') !== before.files[path]) throw new Error('Package changed during export') + files[path] = data + } finally { await handle.close() } + } + const after = await snapshotInstalledSkillDirectory(baseline.inventoryItem, entry) + if (before.fingerprint !== after.fingerprint) throw new Error('Package changed during export') + const archive = zipSync(files) + if (archive.byteLength > MAX_TRANSFER_BYTES) throw new Error('Package exceeds transfer size limit') + const verifyDirectory = await mkdtemp(join(tmpdir(), 'skillhub-export-check-')) + try { await extractZip(archive.slice().buffer, verifyDirectory, {rejectInternalMetadata: true}) } + finally { await rm(verifyDirectory, {recursive: true, force: true}) } + if (archive.byteLength > MAX_TRANSFER_BYTES) throw new Error('Package exceeds transfer size limit') + return { filename: `${selected.slug}.zip`, archive } + } finally { await release() } +} + +/** Reject unsafe or oversized content before fingerprint helpers read whole files. */ +async function assertBoundedTree(directory: string): Promise { + if (await realpath(directory) !== directory) throw new Error('Unsafe package root') + let count = 0 + let bytes = 0 + const walk = async (path: string): Promise => { + const stat = await lstat(path) + if (path !== directory && ++count > MAX_ZIP_ENTRIES) throw new Error('Too many package entries') + if (stat.isSymbolicLink()) throw new Error('Unsafe package entry') + if (stat.isDirectory()) { + for (const entry of await readdir(path)) await walk(join(path, entry)) + } else { + if (!stat.isFile() || stat.size > MAX_SINGLE_FILE_BYTES) throw new Error('Unsafe or oversized package entry') + bytes += stat.size + if (bytes > MAX_PACKAGE_BYTES) throw new Error('Package exceeds expanded size limit') + } + } + await walk(directory) +} diff --git a/cli/src/integrations/transaction-journal.ts b/cli/src/integrations/transaction-journal.ts index cde349866..f2816801e 100644 --- a/cli/src/integrations/transaction-journal.ts +++ b/cli/src/integrations/transaction-journal.ts @@ -5,6 +5,7 @@ import type { OperationStore } from './operation-store' const text = z.string().min(1).max(2048) const source = text.refine(value => { + if (value === 'local:import') return true try { const url = new URL(value); return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password && !url.search && !url.hash } catch { return false } }, 'Expected a credential-free registry identity') diff --git a/cli/src/platform/archive.ts b/cli/src/platform/archive.ts index 677ba7a07..bb9f22a1f 100644 --- a/cli/src/platform/archive.ts +++ b/cli/src/platform/archive.ts @@ -71,6 +71,7 @@ function validateZipCentralDirectory(archive: Uint8Array, rejectInternalMetadata } const destinations = new Map() + const localRanges: Array<{ start: number; end: number }> = [] let offset = centralDirectoryOffset let totalUncompressedSize = 0 const decoder = new TextDecoder() @@ -78,6 +79,10 @@ function validateZipCentralDirectory(archive: Uint8Array, rejectInternalMetadata if (offset + 46 > archive.byteLength || view.getUint32(offset, true) !== CENTRAL_DIRECTORY_SIGNATURE) { throw new Error('invalid zip central directory') } + const flags = view.getUint16(offset + 8, true) + const unixMode = view.getUint32(offset + 38, true) >>> 16 + const kind = unixMode & 0xf000 + if (rejectInternalMetadata && ((flags & 1) || (kind !== 0 && kind !== 0x8000 && kind !== 0x4000))) throw new Error('Unsupported zip entry type') const uncompressedSize = view.getUint32(offset + 24, true) const nameLength = view.getUint16(offset + 28, true) const extraLength = view.getUint16(offset + 30, true) @@ -114,6 +119,23 @@ function validateZipCentralDirectory(archive: Uint8Array, rejectInternalMetadata if (totalUncompressedSize > MAX_PACKAGE_BYTES) { throw new Error('zip total uncompressed size exceeds limit') } + const method = view.getUint16(offset + 10, true) + const compressedSize = view.getUint32(offset + 20, true) + const localOffset = view.getUint32(offset + 42, true) + if ((flags & 1) || ![0, 8].includes(method) || method === 0 && compressedSize !== uncompressedSize) throw new Error('invalid zip compression sizes or method') + if (localOffset + 30 > centralDirectoryOffset || view.getUint32(localOffset, true) !== 0x04034b50) throw new Error('invalid zip local header') + const localNameLength = view.getUint16(localOffset + 26, true) + const payloadStart = localOffset + 30 + localNameLength + view.getUint16(localOffset + 28, true) + const payloadEnd = payloadStart + compressedSize + if (payloadStart > centralDirectoryOffset || payloadEnd > centralDirectoryOffset + || localNameLength !== nameLength || view.getUint16(localOffset + 6, true) !== flags + || view.getUint16(localOffset + 8, true) !== method + || archive.subarray(localOffset + 30, localOffset + 30 + localNameLength).some((byte, index) => byte !== archive[nameStart + index])) throw new Error('inconsistent zip local header') + if (!(flags & 8) && (view.getUint32(localOffset + 18, true) !== compressedSize + || view.getUint32(localOffset + 22, true) !== uncompressedSize + || view.getUint32(localOffset + 14, true) !== view.getUint32(offset + 16, true))) throw new Error('inconsistent zip local sizes') + if (localRanges.some(range => localOffset < range.end && payloadEnd > range.start)) throw new Error('overlapping zip entries') + localRanges.push({ start: localOffset, end: payloadEnd }) offset = nextOffset } } diff --git a/cli/src/services/install-service.ts b/cli/src/services/install-service.ts index 35f14ec65..14b688599 100644 --- a/cli/src/services/install-service.ts +++ b/cli/src/services/install-service.ts @@ -24,6 +24,9 @@ import type { Inventory, InventoryItem } from '../stores/inventory-store' import { acquireSkillTargetLock, orderSkillTargetLocks } from './skill-target-lock' export interface InstallOptions { + /** Internal native import bytes; never read from CLI flags. */ + packageBytes?: Uint8Array + metadataSource?: 'local-import' registry: string token?: string | undefined namespace: string @@ -120,6 +123,9 @@ async function preflightInstallTargets( } export async function installSkill(options: InstallOptions): Promise { + const imported = options.registry === 'local:import' + if (imported !== !!options.packageBytes || imported !== (options.metadataSource === 'local-import') + || imported && (options.namespace !== 'local' || options.version !== 'local' || options.force)) throw new Error('Invalid local package identity') const store = options.inventoryStore ?? new InventoryStore(options.home) await store.ensureWritable() const expectedItem = options.expectedInventoryItem === undefined ? undefined : structuredClone(options.expectedInventoryItem) @@ -154,7 +160,7 @@ export async function installSkill(options: InstallOptions): Promise `${path}:${createHash('sha256').update(path === 'SKILL.md' ? new TextEncoder().encode(content) : new Uint8Array([0,255])).digest('hex')}\n`).join('')).digest('hex') +const target = join(root,'skills/demo') +const operation = (await runtime.acceptInstall({hostInstanceId:runtime.hostInstanceId,ownerId:'session',requestKey:randomUUID(),mode:'new',parameters:{fixture:boundary}}, async()=>({namespace:'local',slug:'demo',version:'local',targetLabel:'Project',targetPaths:[target],context:{sourceIdentity:'local:import',sourceLabel:'Local',sourceRevision:'r',hostLabel:'Host',initiatedFrom:'plaza'}})))! +const operations = await OperationStore.open(stateDirectory) +const accepted = (await operations.get(operation.operationId,'session'))! +await operations.update(accepted.operationId,accepted.ownerId,accepted.revision,{...accepted.operation.status,phase:'staging'}) +await writeFile(join(root,'fixture.json'),JSON.stringify({operationId:operation.operationId,target})) +const observer = await createInstallTransactionObserver(operations,operation.operationId,'session') +const stop = async (point: string) => { if (point === boundary) {process.kill(process.pid,'SIGKILL'); await new Promise(()=>{})} } +await installSkill({registry:'local:import',namespace:'local',slug:'demo',version:'local',force:false,packageBytes:archive,metadataSource:'local-import',inventoryStore:new InventoryStore(join(stateDirectory,'local-imports')),targets:[{agent:'dsh',rootDir:join(root,'skills'),scope:'project',source:'explicit'}],resolved:{namespace:'local',slug:'demo',version:'local',versionId:1,fingerprint,downloadUrl:''},transactionObserver:{...observer,beforePreparation:async value=>{await observer.beforePreparation!(value);await stop('prepared')},afterMove:async value=>{await observer.afterMove!(value);if(value.phase==='install')await stop('after-install')}}}) +throw new Error('Expected kill boundary') diff --git a/cli/test/unit/integrations/native-runtime.test.ts b/cli/test/unit/integrations/native-runtime.test.ts index f1d3b3a7e..8b63a2a1b 100644 --- a/cli/test/unit/integrations/native-runtime.test.ts +++ b/cli/test/unit/integrations/native-runtime.test.ts @@ -1,6 +1,6 @@ import { expect, test } from 'bun:test' import { randomUUID } from 'node:crypto' -import { realpath, mkdir, mkdtemp, rm } from 'node:fs/promises' +import { realpath, mkdir, mkdtemp, rm, readFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { openNativeRuntime } from '../../../src/integrations/native-runtime' @@ -21,6 +21,7 @@ test('native acceptance survives restart, resolves retries before stale referenc sourceRevision: 'original', hostLabel: 'Host', initiatedFrom: 'plaza' } } const accepted = (await first.acceptInstall(request, async () => input))! expect(accepted.phase).toBe('accepted') + expect(JSON.parse(await readFile(join(options.stateDirectory, `${accepted.operationId}.json`), 'utf8')).schemaVersion).toBe(2) expect(JSON.stringify(accepted)).not.toContain(root) for (const privateField of ['targetPaths', 'transaction', 'ownerId', 'requestDigest', 'requestKey']) { expect(accepted).not.toHaveProperty(privateField) diff --git a/cli/test/unit/integrations/package-import-crash.test.ts b/cli/test/unit/integrations/package-import-crash.test.ts new file mode 100644 index 000000000..6d39a39f2 --- /dev/null +++ b/cli/test/unit/integrations/package-import-crash.test.ts @@ -0,0 +1,35 @@ +import {expect,test} from 'bun:test' +import {mkdtemp,realpath,readFile,readdir,rm} from 'node:fs/promises' +import {tmpdir} from 'node:os' +import {join} from 'node:path' +import {fileURLToPath} from 'node:url' +import {openNativeRuntime} from '../../../src/integrations/native-runtime' +import {InventoryStore} from '../../../src/stores/inventory-store' + +test.skipIf(process.platform === 'win32')('killed local import restores private transactions before and after target publication', async()=>{ + const roots: string[]=[] + try { + const cases = await Promise.all(['prepared','after-install'].map(async boundary=>{ + const root=await realpath(await mkdtemp(join(tmpdir(),'skillhub-import-kill-')));roots.push(root) + const child=Bun.spawn([process.execPath,fileURLToPath(new URL('../../fixtures/package-import-crash-child.ts',import.meta.url)),root,boundary],{stdout:'pipe',stderr:'pipe'}) + expect(await child.exited).not.toBe(0) + expect(await new Response(child.stderr).text()).toBe('') + const fixture=JSON.parse(await readFile(join(root,'fixture.json'),'utf8')) as {operationId:string;target:string} + if(boundary==='after-install')expect(await readFile(join(fixture.target,'SKILL.md'),'utf8')).toContain('Local crash fixture') + return {root,...fixture} + })) + // Proper-lockfile target and inventory leases expire after the killed process. + await Bun.sleep(31_500) + for(const fixture of cases){ + const options={stateDirectory:join(fixture.root,'operations'),inventoryHome:join(fixture.root,'shared')} + const runtime=await openNativeRuntime(options) + expect((await runtime.listPending()).map(item=>item.operationId)).toContain(fixture.operationId) + expect((await runtime.recover(fixture.operationId,'session',[fixture.target],async()=>{})).outcome).toBe('restored') + expect(await readdir(join(fixture.root,'skills'))).toEqual([]) + expect((await new InventoryStore(options.inventoryHome).read()).items).toEqual([]) + expect((await new InventoryStore(join(options.stateDirectory,'local-imports')).read()).items).toEqual([]) + expect(await runtime.listPending()).toEqual([]) + expect((await runtime.recover(fixture.operationId,'session',[fixture.target],async()=>{})).outcome).toBe('restored') + } + }finally{await Promise.all(roots.map(root=>rm(root,{recursive:true,force:true})))} +},60_000) diff --git a/cli/test/unit/integrations/package-transfer.test.ts b/cli/test/unit/integrations/package-transfer.test.ts new file mode 100644 index 000000000..408cc629c --- /dev/null +++ b/cli/test/unit/integrations/package-transfer.test.ts @@ -0,0 +1,114 @@ +import { expect, test } from 'bun:test' +import { randomUUID } from 'node:crypto' +import { mkdtemp, realpath, rm, readFile, rename, writeFile, readdir } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { zipSync, unzipSync } from 'fflate' +import { openNativeRuntime } from '../../../src/integrations/native-runtime' +import { previewPackage } from '../../../src/integrations/package-transfer' +import { InventoryStore } from '../../../src/stores/inventory-store' + +test('local import roundtrip preserves resources, isolates shared inventory and survives restart', async () => { + const home = await realpath(await mkdtemp(join(tmpdir(), 'skillhub-transfer-'))) + try { + const options = {stateDirectory: join(home, 'operations'), inventoryHome: join(home, 'shared')} + let runtime = await openNativeRuntime(options) + const files = {'SKILL.md': new TextEncoder().encode('---\nname: demo\ndescription: Test\n---\nHello'), 'asset.bin': new Uint8Array([0, 255, 1]), '.skillhub/examples.json': new TextEncoder().encode('{"example":"案例"}')} + const archive = zipSync(files) + const preview = await runtime.previewPackage(archive, async () => ({name: 'demo'})) + const root = join(home, 'skills') + const acceptance = {namespace: 'local', slug: 'demo', version: 'local', targetLabel: 'Project', targetPaths: [join(root,'demo')], context: {sourceIdentity: 'local:import', sourceLabel: 'Local', sourceRevision: 'r', hostLabel: 'Host', initiatedFrom: 'plaza' as const}} + const request = {hostInstanceId: runtime.hostInstanceId, ownerId: 'session', requestKey: randomUUID(), mode: 'new' as const, parameters: {token: randomUUID()}} + const accepted = (await runtime.acceptInstall(request, async () => acceptance))! + const result = await runtime.executePackageImport({operationId: accepted.operationId, ownerId: 'session', registry: 'local:import', namespace: 'local', slug: 'demo', version: 'local', versionId: 1, fingerprint: preview.fingerprint, root, scope: 'project', archive, authorize: async () => {}, validateStaged: async () => {}}) + expect(result.outcome).toBe('committed') + expect((await readdir(options.stateDirectory)).filter(path => path.endsWith('.json'))).not.toContain(`${accepted.operationId}.json`) + expect((await readdir(join(options.stateDirectory,'activation')).catch(() => [])).filter(path=>path.endsWith('.json'))).not.toContain(`${accepted.operationId}.json`) + expect(JSON.parse(await readFile(join(options.stateDirectory,'local-packages',`${accepted.operationId}.json`),'utf8')).schemaVersion).toBe(3) + expect((await new InventoryStore(options.inventoryHome).read()).items).toEqual([]) + runtime = await openNativeRuntime(options) + const target = {root, scope: 'project' as const} + expect((await runtime.listAllInstalled([target])).items[0]?.registry).toBe('local:import') + expect(await runtime.observeInstallation(accepted.operationId, 'session', [root], async () => true)).toBe(true) + const recovered = await runtime.recover(accepted.operationId, 'session', [join(root, 'demo')], async () => {}) + expect(recovered.outcome).toBe('committed') + const duplicate = (await runtime.acceptInstall({...request, hostInstanceId: runtime.hostInstanceId, requestKey: randomUUID()}, async () => acceptance))! + await expect(runtime.executePackageImport({operationId:duplicate.operationId,ownerId:'session',registry:'local:import',namespace:'local',slug:'demo',version:'local',versionId:1,fingerprint:preview.fingerprint,root,scope:'project',archive,authorize:async()=>{},validateStaged:async()=>{}})).rejects.toThrow() + const selection = {registry:'local:import',namespace:'local',slug:'demo',version:'local'} + await writeFile(join(root,'demo/SKILL.md'), 'locally edited') + expect(await runtime.readInstallationEntry(selection,target)).toBe('locally edited') + const exported = unzipSync((await runtime.exportPackage(selection,target)).archive) + expect(new TextDecoder().decode(exported['SKILL.md'])).toBe('locally edited') + expect(exported['asset.bin']).toEqual(files['asset.bin']) + expect(exported['.skillhub/examples.json']).toEqual(files['.skillhub/examples.json']) + expect(exported['.skillhub/metadata.json']).toBeUndefined() + await rename(join(root,'demo/SKILL.md'),join(root,'demo/SKILL.md.disabled')) + expect(unzipSync((await runtime.exportPackage(selection,target)).archive)['SKILL.md']).toBeDefined() + expect(await readFile(join(root,'demo/SKILL.md.disabled'),'utf8')).toBe('locally edited') + } finally {await rm(home,{recursive:true,force:true})} +}) + +test('preview rejects internal metadata and traversal without invoking validation', async () => { + for (const path of ['../escape', '.skillhub/metadata.json', '/absolute']) { + let called = false + await expect(previewPackage(zipSync({'SKILL.md':new Uint8Array([1]),[path]:new Uint8Array([2])}),async()=>{called=true;return {name:'demo'}})).rejects.toThrow() + expect(called).toBe(false) + } +}) + + +test('preview rejects Unix symlinks and encrypted ZIP flags', async () => { + for (const symlink of [true, false]) { + const archive = zipSync({'SKILL.md':new Uint8Array([1])}) + const view = new DataView(archive.buffer, archive.byteOffset, archive.byteLength) + for (let i = 0; i + 46 <= archive.length; i++) { + if (view.getUint32(i, true) !== 0x02014b50) continue + if (symlink) view.setUint32(i + 38, 0xa1ff0000, true) + else view.setUint16(i + 8, view.getUint16(i + 8, true) | 1, true) + break + } + await expect(previewPackage(archive, async () => ({name:'demo'}))).rejects.toThrow('Unsupported zip entry type') + } +}) + +test('local package seams reject market identities and forged metadata source', async () => { + const {installSkill} = await import('../../../src/services/install-service') + await expect(installSkill({registry:'https://example.test',namespace:'team',slug:'demo',version:'1',force:false,targets:[],packageBytes:new Uint8Array([1]),metadataSource:'local-import'})).rejects.toThrow('Invalid local package identity') + await expect(installSkill({registry:'local:import',namespace:'team',slug:'demo',version:'local',force:false,targets:[],packageBytes:new Uint8Array([1]),metadataSource:'local-import'})).rejects.toThrow('Invalid local package identity') +}) + +test('stale shared inventory claims prevent local import without modifying either source',async()=>{ + const home=await realpath(await mkdtemp(join(tmpdir(),'skillhub-import-stale-'))) + try { + const options={stateDirectory:join(home,'operations'),inventoryHome:join(home,'shared')} + const runtime=await openNativeRuntime(options) + const root=join(home,'skills') + const shared=new InventoryStore(options.inventoryHome) + await shared.upsertTarget('https://registry.example','team','demo','1.0.0',{agent:'dsh',rootDir:root,installDir:join(root,'demo'),installedAt:new Date().toISOString()}) + const before=await readFile(shared.path) + const archive=zipSync({'SKILL.md':new TextEncoder().encode('---\nname: demo\ndescription: demo\n---\nhello')}) + const preview=await runtime.previewPackage(archive,async()=>({name:'demo'})) + const accepted=(await runtime.acceptInstall({hostInstanceId:runtime.hostInstanceId,ownerId:'session',requestKey:randomUUID(),mode:'new',parameters:{preview:'stale'}},async()=>({namespace:'local',slug:'demo',version:'local',targetLabel:'Project',targetPaths:[join(root,'demo')],context:{sourceIdentity:'local:import',sourceLabel:'Local',sourceRevision:'r',hostLabel:'Host',initiatedFrom:'plaza'}})))! + await expect(runtime.executePackageImport({operationId:accepted.operationId,ownerId:'session',registry:'local:import',namespace:'local',slug:'demo',version:'local',versionId:1,fingerprint:preview.fingerprint,root,scope:'project',archive,authorize:async()=>{},validateStaged:async()=>{}})).rejects.toThrow('Registry installation record') + expect(await readFile(shared.path)).toEqual(before) + await expect(readFile(join(root,'demo/SKILL.md'))).rejects.toMatchObject({code:'ENOENT'}) + expect((await new InventoryStore(join(options.stateDirectory,'local-imports')).read()).items).toEqual([]) + }finally{await rm(home,{recursive:true,force:true})} +}) + +test('native Registry install rejects a stale private local claim before network access',async()=>{ + const home=await realpath(await mkdtemp(join(tmpdir(),'skillhub-market-stale-'))) + try { + const options={stateDirectory:join(home,'operations'),inventoryHome:join(home,'shared')} + const runtime=await openNativeRuntime(options) + const root=join(home,'skills') + const local=new InventoryStore(join(options.stateDirectory,'local-imports')) + await local.upsertTarget('local:import','local','demo','local',{agent:'dsh',rootDir:root,installDir:join(root,'demo'),installedAt:new Date().toISOString()}) + const before=await readFile(local.path) + const accepted=(await runtime.acceptInstall({hostInstanceId:runtime.hostInstanceId,ownerId:'session',requestKey:randomUUID(),mode:'new',parameters:{preview:'market'}},async()=>({namespace:'team',slug:'demo',version:'1.0.0',targetLabel:'Project',targetPaths:[join(root,'demo')],context:{sourceIdentity:'https://not-contacted.invalid',sourceLabel:'Market',sourceRevision:'r',hostLabel:'Host',initiatedFrom:'plaza'}})))! + await expect(runtime.executeInstall({operationId:accepted.operationId,ownerId:'session',registry:'https://not-contacted.invalid',namespace:'team',slug:'demo',version:'1.0.0',versionId:1,fingerprint:'sha256:unused',root,scope:'project',authorize:async()=>{},validateStaged:async()=>{}})).rejects.toThrow('local installation record') + expect(await readFile(local.path)).toEqual(before) + await expect(readFile(join(root,'demo/SKILL.md'))).rejects.toMatchObject({code:'ENOENT'}) + expect((await new InventoryStore(options.inventoryHome).read()).items).toEqual([]) + }finally{await rm(home,{recursive:true,force:true})} +}) diff --git a/cli/test/unit/platform/archive.test.ts b/cli/test/unit/platform/archive.test.ts index 73f508698..d26415ed3 100644 --- a/cli/test/unit/platform/archive.test.ts +++ b/cli/test/unit/platform/archive.test.ts @@ -149,3 +149,23 @@ describe('archive helpers', () => { await expect(extractZip(archive.buffer as ArrayBuffer, target)).rejects.toThrow('zip total uncompressed size exceeds limit') }) }) + +test('rejects stored-size lies and reused local offsets before writing', async () => { + for (const attack of ['size', 'offset', 'method', 'payload'] as const) { + const target = await mkdtemp(join(tmpdir(), 'skillhub-invalid-zip-')) + try { + const archive = zipSync({'one.txt':new Uint8Array([1,2,3,4]),'two.txt':new Uint8Array([5,6,7,8])},{level:0}) + const view = new DataView(archive.buffer,archive.byteOffset,archive.byteLength) + const headers: number[] = [] + for (let i = 0; i + 46 <= archive.length; i++) if (view.getUint32(i,true) === 0x02014b50) headers.push(i) + const first = headers[0]! + const second = headers[1]! + if (attack === 'size') view.setUint32(first + 24,0,true) + if (attack === 'offset') view.setUint32(second + 42,view.getUint32(first + 42,true),true) + if (attack === 'method') view.setUint16(first + 10,99,true) + if (attack === 'payload') { view.setUint32(first + 20,archive.length,true); view.setUint32(first + 24,archive.length,true) } + await expect(extractZip(archive.slice().buffer,target,{rejectInternalMetadata:true})).rejects.toThrow() + await expect(readFile(join(target,'one.txt'))).rejects.toMatchObject({code:'ENOENT'}) + } finally { await rm(target,{recursive:true,force:true}) } + } +}) diff --git a/openspec/changes/add-dsh-native-plugin/package-transfer-design.md b/openspec/changes/add-dsh-native-plugin/package-transfer-design.md new file mode 100644 index 000000000..992d7d5a4 --- /dev/null +++ b/openspec/changes/add-dsh-native-plugin/package-transfer-design.md @@ -0,0 +1,51 @@ +# 单技能包导入与导出 + +## 范围与交互 + +本轮只实现 DSH 本地单技能 ZIP 导入/导出,不增加 CLI 命令、服务端 API、登录或发布功能。复用现有 shadcn/Radix 控件及安装范围选择。运行环境检查暂缓。 + +- 已安装页面提供一个次要“导入技能包”入口。选择 ZIP 后,预览技能名称、简介、文件数和安装范围;用户明确确认后才安装。取消预览不安装,不执行包内脚本。 +- 首期包的根目录必须包含单个 `SKILL.md`;不自动发现多技能、套件或嵌套根。采用 DSH 实际解析器验证,解析失败明确拒绝。 +- 同名目标(包括手工技能、不同来源、停用目录、其他安装记录)存在时阻止导入,不提供覆盖或隐式改名。用户可选择另一范围,或自行处理已有技能后重试。 + 对同一可信本地来源、相同指纹且未修改的现有安装,可以核验后返回已安装回执,不重写文件;这不允许替换不同内容或不同来源。 +- 详情右侧“安装管理”的各位置使用明确的“管理+下拉箭头”按钮进入原有菜单,增加“导出技能包”。点击即导出该位置,不使用省略号触发器,不在标题旁增加独立按钮,也不再次弹出位置选择框。安装位置以紧凑分隔行展示范围和状态标签,仅市场安装显示实际版本;本地导入不重复显示“本地技能”。同一技能存在多个位置时由用户打开对应位置菜单明确选择。导出实际文件而不是重新下载发布包,保留本地修改、二进制资源和 `.skillhub/examples.json`。 +- 停用安装导出时只在 ZIP 内把 `SKILL.md.disabled` 还原为 `SKILL.md`,不改变原安装状态。包内同时出现两个入口则拒绝。 +- 导入成功回到已安装列表并显示“本地导入”;可以使用、诊断、启停和卸载。它没有市场详情、市场版本更新或官网跳转;不凭名称或包内元数据认领 Registry 身份。 + +## 来源与兼容 + +导入来源由 Host 创建,不能由 ZIP 声明。内部本地来源标识不是可访问的 Registry 地址,禁止用于 HTTP 请求。导入记录保存在 DSH 私有状态目录,复用库存 v2 读写和目标锁,不能把新类型记录写入 CLI 共享库存或要求旧 CLI 升级。市场安装的库存、元数据和行为保持不变。 + +使用同一操作日志与恢复机制;本地导入操作复用既有扩展日志隔离目录,旧 DSH 普通日志扫描不会读取新来源记录;根据可信操作来源选择对应库存。读取已安装列表时合并两类可信投影,市场更新扫描仍只选择当前 Registry。旧 CLI 对导入目录的普通同名安装仍应拒绝覆盖。 + +## 文件及授权边界 + +- Client 只能上传 ZIP 字节、提交不透明预览引用和安装范围;导出只能提交已安装项引用,不接受任意宿主路径。 +- ZIP 解析复用共享 archive 能力并补齐导入需要的拒绝规则:路径穿越、绝对路径、大小写冲突、重复条目、软链接/特殊文件、加密或不支持的归档、单文件/文件数/总展开体积超限。 +- `.skillhub/metadata.json` 属于安装器内部状态,导出排除、导入拒绝。保留合法作者资源,不把整个 `.skillhub` 目录删除。拒绝携带已知内部事务/锁等保留路径;不声称能自动识别所有作者文件中的秘密。 +- 传输有明确压缩包字节上限;解析、展开和导出也受既有文件数/单文件/总体积上限保护。错误不得把完整宿主路径或包内容回传给模型。 +- 导出检查普通文件树,拒绝软链接及路径别名,并核对读取期间文件变化;不执行任何内容。 +- 预览有期限,绑定会话、cwd、来源修订和 Host 实例;切换上下文后拒绝旧确认。导入执行重验包指纹、目标、策略及冲突,使用既有目标锁、事务日志和恢复,不增加独立文件事务实现。 +- 默认导入“仅此项目”;两个范围的权限仍由 Host 的实际映射和 sandbox policy 决定。拒绝只读/越界,浏览器不能通过改 scope 绕过权限。 + +## Host 私有契约 + +三项 RPC 均受 `RemoteScope('agent')` 保护,不增加 SkillHub 服务端 HTTP API: + +| 方法 | 输入与结果 | +| --- | --- | +| `previewPackageImport` | 来源修订、ZIP base64、取消信号;返回不透明预览引用、名称/简介、文件数/展开字节数和有效期 | +| `confirmPackageImport` | 来源修订、预览引用、范围、幂等请求键和取消信号;返回既有操作回执 | +| `exportInstalledPackage` | 来源修订、精确安装引用和取消信号;返回文件名与 ZIP base64 | + +压缩包传输上限 8 MiB;Host 预览归档保留总量上限 32 MiB,预览有效期复用现有五分钟计划机制。Client 清理请求及结果时不撤销已受理文件事务。导入预览名称及长链接自动换行,完整简介保留在限高滚动区(桌面120px、窄屏96px);短窗口只滚动内容区,安装范围与底部操作保持可见,下拉菜单不被内容区裁切。导入弹窗沿用安装/下载进度的视觉,预览与范围下方保留紧凑结果区;确认后显示真实阶段,完成回执显示“导入成功”,异常或回执不可读时显示待核验,不伪造百分比。安装范围提交后保留且锁定,完成前后高度保持稳定。仅核对到对应本地来源、技能、范围的完整可用安装后展示“使用技能”,点击时重新核对并走已有原生使用流程,不自动发送。导入弹窗关闭后恢复入口焦点;导出复用位置菜单的键盘与焦点行为,不增加弹窗;导入事务尚未结束、入口仍禁用时回退到列表搜索框。 + +## 验收 + +1. 含脚本、二进制与多语言案例的导出/导入往返逐文件字节一致,内部元数据不传播。 +2. 本地修改被导出;停用安装导出后入口规范化但原文件不变。 +3. 已存在目录、跨来源和用户/项目同名的冲突均不覆盖;只修改选择的位置。 +4. 恶意/损坏/超限 ZIP 被拒绝,无目标文件和库存变更。 +5. 取消、重复确认、会话/来源变化、权限变化及并发安装保持目标与记录一致;失败或中断可按既有机制恢复。 +6. 导入项可使用、启停、诊断和卸载,不访问 Registry;市场来源功能及旧 CLI 库存 v2 兼容。 +7. Host 契约、共享核心、UI 交互分别验证;实际 DSH 浏览器核对明暗、窄屏、键盘、上传与下载。未运行的模型/平台验收单独记录,不用静态截图替代业务验证。 diff --git a/openspec/changes/add-dsh-native-plugin/proposal.md b/openspec/changes/add-dsh-native-plugin/proposal.md index baca22657..a82591e66 100644 --- a/openspec/changes/add-dsh-native-plugin/proposal.md +++ b/openspec/changes/add-dsh-native-plugin/proposal.md @@ -46,6 +46,7 @@ - [详细实现方案](engineering-blueprint.md) - [本地生命周期](lifecycle-design.md) - [DSH 原生接入](dsh-integration-design.md) +- [单技能包导入与导出](package-transfer-design.md):DSH 本地 ZIP 预览与确认、导出实际内容、本地来源与旧版兼容。 ## 安装级启停增量 diff --git a/openspec/changes/add-dsh-native-plugin/specs/dsh-skill-consumption/spec.md b/openspec/changes/add-dsh-native-plugin/specs/dsh-skill-consumption/spec.md index 91a602fc5..0095a7857 100644 --- a/openspec/changes/add-dsh-native-plugin/specs/dsh-skill-consumption/spec.md +++ b/openspec/changes/add-dsh-native-plugin/specs/dsh-skill-consumption/spec.md @@ -459,6 +459,26 @@ The installed view SHALL check current managed installations only on explicit us - **THEN** a bounded Host-owned scan reads and indexes the trusted inventory once, validates only the requested target and inventory revision per result, and shares remote version resolution for the same source and skill within that scan - **AND** inventory or context changes invalidate the scan, scan resources expire or are released on cancellation, and mutation preparation retains its independent full validation +### Requirement: Explicit single-skill local package transfer +The plugin SHALL import a single ZIP with a valid root SKILL.md only after preview and explicit confirmation. Local imports SHALL remain distinct from Registry releases and SHALL NOT participate in Registry update checks. Import and export SHALL NOT execute packaged scripts or require Registry login. Implementation and limits are defined in package-transfer-design.md. + +#### Scenario: Import a valid package +- **WHEN** the user selects a valid ZIP and confirms an available installation scope +- **THEN** the Host revalidates the exact preview bytes, trusted target and effective write policy before installation +- **AND** the installation appears as a local import with use, activation, diagnosis and precise removal +- **AND** local records do not extend or migrate the shared CLI v2 inventory + +#### Scenario: Conflicting or untrusted import +- **WHEN** the target is occupied, the archive is unsafe or oversized, the preview has expired, or its session context has changed +- **THEN** the operation SHALL NOT overwrite an existing skill or accept an unverified Registry identity from the archive +- **AND** a cancelled preview SHALL NOT create a target installation + +#### Scenario: Export current local content +- **WHEN** a user selects export for an exact installation location +- **THEN** the ZIP preserves the actual local content, resources and authored examples while excluding installer metadata +- **AND** a disabled entry is normalized to SKILL.md in the ZIP without enabling the original installation +- **AND** unsafe file trees, over-limit contents or reads inconsistent with the selected snapshot are rejected + ### Requirement: Shared state remains compatible with released consumers New lifecycle operations SHALL retain the strict v2 shared inventory format readable by released CLI 0.2.0. Activation state SHALL be derived from the verified entry file of the exact managed installation, without an additional writable activation authority. Ordinary operation journals SHALL remain readable by released DSH 0.5.0; activation-specific journals SHALL NOT prevent unrelated ordinary operations in that consumer. diff --git a/openspec/changes/add-dsh-native-plugin/tasks.md b/openspec/changes/add-dsh-native-plugin/tasks.md index 1e0071e3c..30538410f 100644 --- a/openspec/changes/add-dsh-native-plugin/tasks.md +++ b/openspec/changes/add-dsh-native-plugin/tasks.md @@ -452,3 +452,12 @@ - [x] 51.5 独立评审与相关回归、平台验证分别留证;真实尝试Windows执行,macOS无环境时保留未验证边界;不发布或默认保留新预览。 第51章验证边界:CLI冻结全量869测试与build通过,DSH完整709测试、build/type/lint通过。Linux及原生Windows Bun/Node真实16强杀场景矩阵通过,结果核验childExecutable;Windows旧专项采用既有15秒配置通过,额外保护6通过1符号链接权限跳过。macOS原生实机与Windows官方DSH Host未运行。历史CONTEXT_STALE未复现可证根因,仅补固定内部诊断,不宣称根因修复;原有错误码/文案/权限条件及公开Remote工具结构保留。 + +## 52. 单技能包导入与导出 + +- [x] 52.1 按 package-transfer-design.md 实现包预检、导出及 DSH 私有本地来源,保持共享库存 v2。 +- [x] 52.2 接入 Host 会话授权、预览确认、文件保护及既有事务恢复。 +- [x] 52.3 已安装导入入口、详情安装位置菜单直接导出和本地来源展示,复用已有控件。 +- [x] 52.4 核心/Host/UI 回归、恶意 ZIP 拒绝、兼容验证和实际浏览器验收;更新文档与验证边界。 + +第52章验证边界:Linux CLI 完整877测试、DSH完整722测试及build/typecheck/lint通过;真实DSH 0.2.1-rc.2浏览器完成项目/用户导入、导出字节往返、原生案例填入、启停卸载、可用性、明暗/窄屏及键盘焦点。公开旧DSH0.6.1核心启动/查询/普通受理与旧CLI0.2.0查询补验通过;新增导入两阶段Linux真实SIGKILL恢复通过。未运行新增功能的RC0.2.0实际Host、原生Windows/macOS、真实模型或PR CI;未提交、合并或发布,不能据此宣称发布验收完成。 diff --git a/openspec/changes/add-dsh-native-plugin/verification.md b/openspec/changes/add-dsh-native-plugin/verification.md index 4d6a1179e..4cb92daed 100644 --- a/openspec/changes/add-dsh-native-plugin/verification.md +++ b/openspec/changes/add-dsh-native-plugin/verification.md @@ -578,3 +578,33 @@ DSH 0.6.0 发布检查在 Windows / DSH 0.2.1-rc.2 的 `install-host` 阶段两 后续固定提交 `a431833b33bcf7523949537c50b9409c00c70ce3` 的 [CI 41011761831](https://github.com/iflytek/skillhub/actions/runs/41011761831) 已通过全部 14 项 DSH 检查。Windows / Host 0.2.1-rc.2 的启停与关闭监听场景准备分别耗时 348044ms、295943ms;Host 0.2.0-rc.2 分别为 291219ms、322063ms,均在全新 Profile 中通过真实探针。此前安装接受断言失败本轮未复现;新增诊断保留其固定状态和错误码,不修改断言。 本机部分缓存复测仍在 600787ms 超时,因此上述结果证明该固定提交的 CI 矩阵通过,不保证所有 Windows 环境在 600 秒内完成。旧 `dsh-v0.6.0` 标签保持不变;后续发布候选调整为 DSH 0.6.1,使用独立新标签。CLI 0.3.0 已发布,不重复发布,也不发布 SkillHub 应用 Release。0.6.1 发布身份、安装包及公开 npm 验收按发布流程单独验证。 + + +## 2026-11-03 单技能包导入与导出(本地实现,未发布) + +- CLI 完整 877 测试通过,DSH 完整 722 测试、12922 断言通过;两端 build/typecheck/lint 通过,OpenSpec strict 校验通过。 +- Linux 真实 DSH 浏览器验证项目/用户导入、精确位置导出、四文件 ZIP 字节往返、原生发现/案例填入、项目停用/启用、用户位置卸载及可用性检查。覆盖暗色/亮色、390px 弹窗、真实文件选择器、Escape 与焦点返回;没有模型调用或自动发送。 +- 使用已保存的公开 DSH 0.6.1 核心包,验证新版导入后旧版启动、pending 查询、原库存投影和普通操作受理;公开 CLI 0.2.0 查询成功。本地来源库存和日志不进入旧读者扫描的位置。 +- 新增 Linux 两阶段真实 SIGKILL 导入恢复:持久准备后和目标发布后/库存提交前;重启恢复、原库存保持及重复恢复幂等通过。不是实际 DSH Host 强杀,也不代表 Windows/macOS 验收。 +- 独立评审发现并修复 ZIP 声明大小绕过、旧日志兼容和两库存失效归属冲突;最终无 blocker/HIGH。实际浏览器另修复本地技能的市场状态误导入口及关闭弹窗焦点。 +- 未运行本轮新增功能的 DSH 0.2.0-rc.2 实际 Host、原生 Windows/macOS、PR CI 或发布矩阵。没有提交、推送、合并、npm 发布或 SaaS 部署。本机报告和候选包留在仓库外;本次预览检查后关闭。 + + +### 导出入口精简(同轮人工反馈) + +移除标题旁独立更多按钮及再次选择位置的弹窗。导出合并到右侧安装管理每个位置已有菜单,直接下载所选安装。DSH完整check(build/typecheck/lint及722测试)通过;实际浏览器验证项目/用户两处下载、无标题按钮/额外弹窗、390px菜单,分别核对ZIP字节与所选目录一致。Host/CLI及服务端契约未改变;仅更新本轮隔离预览Client,保留人工验收入口运行。 + + +### 安装管理侧栏局部优化(同轮人工反馈) + +右侧安装位置改为紧凑分隔行,显示范围与浅色状态标签;市场版本另列,本地导入不重复显示“本地技能”。以明确的“管理+下拉箭头”替代省略号,并将停用安装的启用动作收进该菜单,保留原确认与精确位置语义。窄屏侧栏与详情齐宽。完整DSH check通过722测试、12925断言;真实浏览器覆盖明暗、单/双安装位置、390px菜单及焦点返回、两个位置直接下载。独立源码评审无blocker/HIGH,未变更Host/CLI/API;保持当前人工预览运行。 + + +### 导入预览长内容保护(同轮人工反馈) + +导入弹窗使用独立限高的完整简介滚动区,名称及长链接自动换行;短视口内容区收缩,安装范围和关闭/确认操作保持可见。未改变导入确认、Host或CLI契约。完整DSH check通过723测试、12931断言及build/typecheck/lint,OpenSpec严格校验和diff检查通过。真实Chrome145.0.7632.6上传三种ZIP(普通、1000字符多段简介/113字符名称、1000字符连续链接),在1440×1000、390×844、390×480、320×568共12组预览中核对无横向溢出、简介完整且限高可滚动、底部操作可见、安装范围下拉及Escape焦点返回正常;未点击确认导入,保留人工现有安装。仓库外证据:`long-import-result.json`、`long-import-check.log`与对应截图。隔离预览Client已更新,入口继续运行;本轮未验证发布、CI或其他操作系统。 + + +### 导入完成态与安装进度一致(同轮人工反馈) + +预览/安装范围下方新增紧凑结果区,复用既有安装进度轨道,按真实阶段展示导入状态;完成回执显示“导入成功”,未知恢复及回执读取失败不显示成功入口。范围提交后保留锁定,精确读取本地来源与所选范围的可用安装后提供原生“使用技能”,点击再次核对库存。完整DSH check(build/typecheck/lint、725测试/12941断言)通过。真实Chrome145.0.7632.6完成唯一命名ZIP的项目级导入,完成前后弹窗均445.65625px高,390×480/320×568按钮可见;点击使用进入原生案例选择并填入输入框,未发送消息/调用模型。追加12组长内容ZIP预览全部通过;本轮不改Host/CLI/HTTP API,未发布或运行CI/其他操作系统验收。仓库外证据:`import-result-check.log`、`success-flow-result.json`、`long-import-result.json`和对应截图;本地人工预览保持运行。 diff --git a/plugins/dsh/README.en.md b/plugins/dsh/README.en.md index 7ba52a5b8..0d10698a9 100644 --- a/plugins/dsh/README.en.md +++ b/plugins/dsh/README.en.md @@ -23,6 +23,14 @@ In the installed card’s More menu, “管理安装” opens skill details, whe An active session is required. Shadowed skills, modified files, disabled user invocation or changed context are reported without modifying the draft. Historical receipts are not proof of current installation. This feature is available from `0.4.0`. +## Local package transfer (in development, not published) + +Use **Import skill package** in the installed view to select a ZIP containing a root `SKILL.md`, preview it, choose the current project or all projects, and confirm. Existing same-name directories are never overwritten. The first version accepts one skill per archive, up to 8 MiB compressed; existing expanded-size, file-count and per-file limits still apply. + +Imports are identified as local packages, support use, diagnosis, activation and removal, and never receive Registry update checks. Import does not require Registry login or connectivity and does not execute packaged scripts. Import records remain in DSH-private state without extending the shared CLI inventory; older versions do not list these records. + +In the detail's installation management panel, each location's Manage menu exports that exact installation directly, without an extra location dialog. The ZIP contains its actual contents, including local edits, resources and `.skillhub/examples.json`, while excluding installer metadata. Exporting a disabled installation normalizes the entry inside the ZIP without enabling the original. Review authored files before sharing; export does not automatically redact private content. + ## Requirements and validation scope | Component | Requirement or scope | diff --git a/plugins/dsh/README.md b/plugins/dsh/README.md index 105d3244a..4035b19fa 100644 --- a/plugins/dsh/README.md +++ b/plugins/dsh/README.md @@ -23,6 +23,14 @@ SkillHub 的 DSH 原生插件。在 DSH 侧栏打开 **技能中心**,匿名 需要当前活动会话。被项目同名技能覆盖、本地文件变更、禁止用户调用或会话/来源变化时会提示原因;历史回执不能代替当前安装状态。此功能自 `0.4.0` 起提供。 +## 本地技能包导入与导出(开发中,未发布) + +在“已安装”页面点击“导入技能包”,选择根目录含 `SKILL.md` 的 ZIP。预览后选择“仅此项目”或“所有项目”,确认才会安装;已有同名目录时拒绝覆盖。首期不支持套件、多技能包或自动识别嵌套目录,压缩包最多 8 MiB,展开仍受共享安装核心的文件数和大小限制。 + +导入项显示“本地导入”,可以使用、诊断、启停和卸载,不参与市场更新检查。导入无需登录或 Registry 连接,不会执行包内脚本。包内安装器元数据不能用于认领市场来源;本地导入记录位于 DSH 私有状态目录,不改写旧 CLI 共享库存。旧版本不会显示这些导入记录。 + +在技能详情右侧“安装管理”中,打开目标位置的“管理”菜单,选择“导出技能包”即可下载 ZIP。导出包含该位置的实际文件及本地修改,保留资源和 `.skillhub/examples.json`,排除 `.skillhub/metadata.json`。停用安装只在 ZIP 内恢复标准入口,不启用原安装。导出不会自动清理作者文件中的私密内容,分享前需自行核对。 + ## 环境与验证范围 | 项目 | 要求或范围 | diff --git a/plugins/dsh/src/client/detail-content.tsx b/plugins/dsh/src/client/detail-content.tsx index d5b954a05..553d22c83 100644 --- a/plugins/dsh/src/client/detail-content.tsx +++ b/plugins/dsh/src/client/detail-content.tsx @@ -7,13 +7,13 @@ import { stripMarkdownFrontmatter } from './markdown-content.js'; import { MarkdownStyles } from './markdown-styles.js'; import '../../lib/typert.remote-client.js'; -export function DetailContent({ detail, modes, remote, retry, onSelectVersion, versionActionLabel, cacheIdentity, onContextStale }: { - detail: SkillDetail; modes: SkillHubConfig['detailTabs']; +export function DetailContent({ detail, modes, remote, retry, onSelectVersion, versionActionLabel, cacheIdentity, onContextStale, localPackage = false }: { + localPackage?: boolean; detail: SkillDetail; modes: SkillHubConfig['detailTabs']; remote: TypertRemoteNamespaceMap['skillhub']; retry: () => void; onSelectVersion?(version: string): void; versionActionLabel?: string; cacheIdentity?: string; onContextStale?(): void; }) { return <> - + {detail.documentation.state === 'error' ?

当前版本的说明暂时不可读取。

:
{alt ? `[图片:${alt}]` : '[图片]'}, diff --git a/plugins/dsh/src/client/detail-tabs.tsx b/plugins/dsh/src/client/detail-tabs.tsx index 92e191f68..35f81a82f 100644 --- a/plugins/dsh/src/client/detail-tabs.tsx +++ b/plugins/dsh/src/client/detail-tabs.tsx @@ -12,8 +12,8 @@ import { readCacheOptions } from './read-cache.js'; type Remote = TypertRemoteNamespaceMap['skillhub']; type Tab = 'details' | 'versions' | 'securityAudit' | 'reviews'; const names: Record = { details: '详情', versions: '版本', securityAudit: '安全审核', reviews: '评论' }; -export function DetailTabs({ detail, modes, remote, children, onSelectVersion, versionActionLabel, cacheIdentity, onContextStale }: { - detail: SkillDetail; modes: SkillHubConfig['detailTabs']; remote: Remote; children: ReactNode; onSelectVersion?(version: string): void; versionActionLabel?: string; cacheIdentity?: string; onContextStale?(): void; +export function DetailTabs({ detail, modes, remote, children, onSelectVersion, versionActionLabel, cacheIdentity, onContextStale, localPackage = false }: { + localPackage?: boolean; detail: SkillDetail; modes: SkillHubConfig['detailTabs']; remote: Remote; children: ReactNode; onSelectVersion?(version: string): void; versionActionLabel?: string; cacheIdentity?: string; onContextStale?(): void; }) { const identity = cacheIdentity ?? JSON.stringify([detail.namespace, detail.slug, detail.version]); const client = useQueryClient(); @@ -23,12 +23,12 @@ export function DetailTabs({ detail, modes, remote, children, onSelectVersion, v const [selected, setSelected] = useState(saved?.selected ?? 'details'); useEffect(() => { client.setQueryData(['skillhub-detail-ui', identity], { selected, pages }); }, [client, identity, selected, pages]); const visible = (Object.keys(names) as Tab[]).filter(tab => tab === 'details' - || modes[tab] === 'show' || (modes[tab] === 'auto' && detail.tabs[tab] === 'available')); + || !localPackage && (modes[tab] === 'show' || (modes[tab] === 'auto' && detail.tabs[tab] === 'available'))); const active = visible.includes(selected) ? selected : 'details'; return setSelected(value as Tab)}> {visible.map(tab => {names[tab]})} {visible.map(tab => - {active !== tab ? null : tab === 'details' ? <>
{children}
SKILL.md当前版本 {detail.version}
: tab === 'securityAudit' ? <>

当前来源未提供公开审核信息

当前来源的审核信息不支持匿名读取。

请检查技能内容与来源,不能据此判断技能已通过安全审核。

审核状态取决于当前来源提供的信息
+ {active !== tab ? null : tab === 'details' ? <>
{children}
SKILL.md{!localPackage && 当前版本 {detail.version}}
: tab === 'securityAudit' ? <>

当前来源未提供公开审核信息

当前来源的审核信息不支持匿名读取。

请检查技能内容与来源,不能据此判断技能已通过安全审核。

审核状态取决于当前来源提供的信息
: <> setPages(previous => ({ ...previous, [tab]: page }))} onContextStale={onContextStale} tab={tab} token={detail.detailToken} remote={remote} detail={detail} onSelectVersion={onSelectVersion} versionActionLabel={versionActionLabel} />}
)} diff --git a/plugins/dsh/src/client/index.tsx b/plugins/dsh/src/client/index.tsx index 925f9d350..b3ff1a813 100644 --- a/plugins/dsh/src/client/index.tsx +++ b/plugins/dsh/src/client/index.tsx @@ -193,6 +193,7 @@ export async function apply(ctx: Context): Promise<() => Promise> { receipt.assertCurrent(); return { sourceRevision: source.value.sourceRevision, list: installed.value }; }), + exportPackage: (revision, itemKey, signal) => call(remote => remote.skillhub.exportInstalledPackage(revision, itemKey, signal)), availability: (revision, itemKey, signal) => call(remote => remote.skillhub.checkAvailability(revision, itemKey, signal)), check: (revision, itemKey, signal) => call(remote => remote.skillhub.checkUpdate(revision, itemKey, signal)), begin: (revision, itemKey, action, version, requestKey, signal) => call(remote => remote.skillhub.beginConversationManagement(revision, itemKey, action, version, requestKey, signal)), @@ -315,6 +316,9 @@ export async function apply(ctx: Context): Promise<() => Promise> { const scope = ctx.sessions.scope(SessionId(sessionId)); if (!scope) throw new Error('当前会话已关闭,请重新打开会话。'); return withSessionRemote(scope, remote => remote.skillhub.listInstalled(revision, signal)); + }, packages: { + preview: async (...args) => { const scope = ctx.sessions.scope(SessionId(sessionId)); if (!scope) throw new Error('当前会话不可用。'); return withSessionRemote(scope, remote => remote.skillhub.previewPackageImport(...args)); }, + confirm: async (...args) => { const scope = ctx.sessions.scope(SessionId(sessionId)); if (!scope) throw new Error('当前会话不可用。'); return withSessionRemote(scope, remote => remote.skillhub.confirmPackageImport(...args)); }, }, detail: async (revision, itemKey, signal) => { const scope = ctx.sessions.scope(SessionId(sessionId)); if (!scope) throw new Error('当前会话已关闭,请重新打开会话。'); diff --git a/plugins/dsh/src/client/installed-card-metadata.tsx b/plugins/dsh/src/client/installed-card-metadata.tsx new file mode 100644 index 000000000..a7662c208 --- /dev/null +++ b/plugins/dsh/src/client/installed-card-metadata.tsx @@ -0,0 +1,21 @@ +import type { InstalledSkillList } from '../host/types.js'; +import { CardDescription } from './ui.js'; + +type Item = InstalledSkillList['items'][number]; +export function installedCardVersions(items: Item[]) { + if (items[0]?.sourceKind === 'local-import') { + const scopes = [...new Set(items.map(item => item.scope === 'user' ? '所有项目' : '仅此项目'))].join(' · '); + return { label: scopes, title: scopes }; + } + const versions = [...new Set(items.map(item => item.version))]; + return { label: versions.length === 1 ? `v${versions[0]}` : `多个版本 · ${versions.map(version => `v${version}`).join(' / ')}`, + title: items.map(item => `${item.scope === 'user' ? '所有项目' : '仅此项目'} · v${item.version}`).join(';') }; +} +export function InstalledCardMetadata({ items }: { items: Item[] }) { + const identity = items[0]; + if (!identity) return null; + const versions = installedCardVersions(items); + return + {identity.sourceKind === 'local-import' ? versions.label : `${versions.label} · @${identity.namespace}/${identity.slug}`} + ; +} diff --git a/plugins/dsh/src/client/installed-skills.tsx b/plugins/dsh/src/client/installed-skills.tsx index 99bf27efe..b3b58cc33 100644 --- a/plugins/dsh/src/client/installed-skills.tsx +++ b/plugins/dsh/src/client/installed-skills.tsx @@ -1,3 +1,6 @@ +import { InstalledCardMetadata } from './installed-card-metadata.js'; +export { installedCardVersions } from './installed-card-metadata.js'; +import { PackageImport, type PackageTransferServices } from './package-transfer.js'; import { ChangePreview } from './change-preview.js'; import * as DropdownMenu from '@radix-ui/react-dropdown-menu'; import { checkInstalledUpdates, updateFailed, type UpdateResult } from './update-overview.js'; @@ -16,11 +19,12 @@ import { DetailContent } from './detail-content.js'; import { RemovalHistory, type RemovalServices } from './removal-control.js'; import { InstalledStyles } from './installed-styles.js'; import type { InstalledNavigation } from './installed-navigation.js'; -import { Badge, Button, Card, CardHeader, CardTitle, CardDescription } from './ui.js'; +import { Badge, Button, Card, CardHeader, CardTitle } from './ui.js'; import { SkillAvatar } from './skill-card.js'; export interface InstalledServices extends UpgradeServices, RemovalServices { management?: ManagementViewServices; + packages?: PackageTransferServices; sessionId: string; context?: { getSnapshot(): number; subscribe(listener: () => void): () => void }; skillUse?: SkillUseServices; @@ -34,7 +38,8 @@ export interface InstalledServices extends UpgradeServices, RemovalServices { type Item = InstalledSkillList['items'][number]; export function installedCardBadges(items: Item[], results: Record, verified: boolean) { const badges: { label: string; tone: 'neutral' | 'warning' | 'info' }[] = []; - if (items[0]?.currentSource === false) badges.push({ label: '其他来源', tone: 'info' }); + if (items[0]?.sourceKind === 'local-import') badges.push({ label: '本地导入', tone: 'info' }); + else if (items[0]?.currentSource === false) badges.push({ label: '其他来源', tone: 'info' }); const summary = verified ? skillInstallationSummary(items) : '安装待核验'; if (summary !== '已安装') badges.push({ label: summary, tone: summary === '已停用' ? 'neutral' : 'warning' }); if (items.some(item => updateFailed(results[item.itemKey]))) badges.push({ label: '检查失败', tone: 'warning' }); @@ -45,11 +50,6 @@ export function installedCardBadges(items: Item[], results: Record item.version))]; - return { label: versions.length === 1 ? `v${versions[0]}` : `多个版本 · ${versions.map(version => `v${version}`).join(' / ')}`, - title: items.map(item => `${item.scope === 'user' ? '所有项目' : '仅此项目'} · v${item.version}`).join(';') }; -} export function installedUpdateKeys(inventory: Item[], results: Record, retry: boolean, group?: Item[]) { return inventory.filter(item => item.currentSource !== false && (!group || group.some(target => target.itemKey === item.itemKey))) .map(item => item.itemKey).filter(key => !retry || updateFailed(results[key])); @@ -172,19 +172,19 @@ export function InstalledSkills({ services, sourceRevision, source, remote, mode

{selected.slug}

-

@{selected.namespace}/{selected.slug} · 文档版本 {selected.version}

+

{selected.sourceKind === 'local-import' ? '本地导入' : `@${selected.namespace}/${selected.slug} · 文档版本 ${selected.version}`}

{changeIntent && services.changes ? { setSelected(null); void query.refetch(); }} onClose={() => { setChangeIntent(undefined); void query.refetch(); void detail.refetch(); void services.management?.client.invalidateQueries({ queryKey: ['skillhub-local-summary', services.sessionId, sourceRevision] }); }} /> : <> {detail.isPending ?

正在读取技能说明…

: detail.isError ?

{detail.error.message}

- : detail.data.content.state === 'local-only' ?

{selected.currentSource === false ? '此技能来自其他来源,可在右侧管理本地安装。' : '远端说明暂不可用,可在管理安装中查看本地状态。'}

- : { void detail.refetch(); }} cacheIdentity={JSON.stringify([services.sessionId, sourceRevision, selected.namespace, selected.slug, detail.data.content.detail.version])} onContextStale={() => { void detail.refetch(); }} />}} + : detail.data.content.state === 'local-only' ?

{selected.sourceKind === 'local-import' ? '本地技能文件暂不可读取,请核对安装状态。' : selected.currentSource === false ? '此技能来自其他来源,可在右侧管理本地安装。' : '远端说明暂不可用,可在管理安装中查看本地状态。'}

+ : { void detail.refetch(); }} cacheIdentity={JSON.stringify([services.sessionId, sourceRevision, selected.namespace, selected.slug, detail.data.content.detail.version])} onContextStale={() => { void detail.refetch(); }} />}}
; const term = keyword.trim().toLocaleLowerCase(); const groups = allGroups.filter(items => filter === 'all' || items.some(item => filter === 'updates' ? results[item.itemKey]?.state === 'upgradable' : updateFailed(results[item.itemKey]))).filter(items => !term || items.some(item => `@${item.namespace}/${item.slug} ${item.displayName ?? ''} ${item.version}`.toLocaleLowerCase().includes(term))); return
-