feat(dsh): import and export local skill packages

Signed-off-by: XiaoSeS <87064762+XiaoSeS@users.noreply.github.com>
This commit is contained in:
XiaoSeS 2026-11-03 20:13:56 +08:00
parent 3ab53d1740
commit 8c4d3bb55a
43 changed files with 1074 additions and 99 deletions

View file

@ -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 {

View file

@ -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')

View file

@ -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'

View file

@ -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<NativeRecoveryResult>
inspectChanges(selected: UpgradeSelection, target: InstalledProjectionTarget): Promise<LocalChangesSnapshot>
readChangeDiff(snapshot: Extract<LocalChangesSnapshot, {status: 'ready'}> | VersionChangesSnapshot, path: string): Promise<BoundedFileDiff>
prepareVersionChanges(selected: UpgradeSelection, target: InstalledProjectionTarget,

View file

@ -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<NativeRecoveryResult> {
export async function executeNativeInstall(operations: OperationStore, inventory: InventoryStore, request: NativeInstallExecution & { archive?: Uint8Array }): Promise<NativeRecoveryResult> {
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,

View file

@ -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,

View file

@ -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<NativeRuntime> {
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)
})

View file

@ -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<OperationRecord | undefined> {
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<void> {
private localPackagePath(operationId: string): string { return join(this.root, 'local-packages', `${id.parse(operationId)}.json`) }
private async validateExtendedDirectory(directory = 'activation'): Promise<void> {
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<void> {
const path = join(this.root, 'activation')
private async prepareExtendedDirectory(directory = 'activation'): Promise<void> {
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<void> {
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()

View file

@ -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<PackageInspection> {
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<string, Uint8Array> = {}
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<void> {
if (await realpath(directory) !== directory) throw new Error('Unsafe package root')
let count = 0
let bytes = 0
const walk = async (path: string): Promise<void> => {
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)
}

View file

@ -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')

View file

@ -71,6 +71,7 @@ function validateZipCentralDirectory(archive: Uint8Array, rejectInternalMetadata
}
const destinations = new Map<string, boolean>()
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
}
}

View file

@ -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<InstallResult> {
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<InstallResu
await options.transactionObserver?.beforeTargetMutation?.([...canonicalDirs])
const client = options.client ?? new SkillHubClient(options.registry, options.token)
const resolved = options.resolved ?? await client.resolve(options.namespace, options.slug, options.version)
const response = resolved.downloadUrl
const response = options.packageBytes ? new Response(options.packageBytes.slice().buffer) : resolved.downloadUrl
? await client.downloadFromUrl(resolved.downloadUrl)
: await client.download(options.namespace, options.slug, resolved.version)
const buffer = await readBoundedResponseBody(response)
@ -196,7 +202,7 @@ export async function installSkill(options: InstallOptions): Promise<InstallResu
versionId: resolved.versionId,
fingerprint: resolved.fingerprint,
files: snapshot.files,
source: 'skillhub',
source: options.metadataSource ?? 'skillhub',
agent: target.agent,
installedAt
}, null, 2))

View file

@ -37,7 +37,7 @@ export async function readInstalledSkillMetadata(skillDir: string): Promise<Inst
return { status: 'invalid', reason: `metadata field "${field}" must be a non-empty string` }
}
}
if (value.source !== undefined && value.source !== 'skillhub') {
if (value.source !== undefined && value.source !== 'skillhub' && !(value.source === 'local-import' && value.registry === 'local:import' && value.namespace === 'local' && value.version === 'local')) {
return { status: 'invalid', reason: 'metadata field "source" must be "skillhub"' }
}
if (value.schemaVersion !== undefined && value.schemaVersion !== 1) {

View file

@ -0,0 +1,27 @@
import { randomUUID, createHash } from 'node:crypto'
import { writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { zipSync } from 'fflate'
import { openNativeRuntime } from '../../src/integrations/native-runtime'
import { OperationStore } from '../../src/integrations/operation-store'
import { createInstallTransactionObserver } from '../../src/integrations/transaction-journal'
import { installSkill } from '../../src/services/install-service'
import { InventoryStore } from '../../src/stores/inventory-store'
const [root, boundary] = process.argv.slice(2)
if (!root || !boundary) throw new Error('Missing fixture arguments')
const stateDirectory = join(root,'operations')
const runtime = await openNativeRuntime({stateDirectory, inventoryHome:join(root,'shared')})
const content = '---\nname: demo\ndescription: Local crash fixture\n---\nhello'
const archive = zipSync({'SKILL.md':new TextEncoder().encode(content),'asset.bin':new Uint8Array([0,255])})
const fingerprint = 'sha256:' + createHash('sha256').update(['SKILL.md','asset.bin'].map(path => `${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')

View file

@ -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)

View file

@ -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)

View file

@ -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})}
})

View file

@ -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}) }
}
})

View file

@ -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 浏览器核对明暗、窄屏、键盘、上传与下载。未运行的模型/平台验收单独记录,不用静态截图替代业务验证。

View file

@ -46,6 +46,7 @@
- [详细实现方案](engineering-blueprint.md)
- [本地生命周期](lifecycle-design.md)
- [DSH 原生接入](dsh-integration-design.md)
- [单技能包导入与导出](package-transfer-design.md):DSH 本地 ZIP 预览与确认、导出实际内容、本地来源与旧版兼容。
## 安装级启停增量

View file

@ -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.

View file

@ -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;未提交、合并或发布,不能据此宣称发布验收完成。

View file

@ -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`和对应截图;本地人工预览保持运行。

View file

@ -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 |

View file

@ -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 内恢复标准入口,不启用原安装。导出不会自动清理作者文件中的私密内容,分享前需自行核对。
## 环境与验证范围
| 项目 | 要求或范围 |

View file

@ -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 <>
<MarkdownStyles />
<DetailTabs key={cacheIdentity ?? `${detail.namespace}/${detail.slug}/${detail.version}`} cacheIdentity={cacheIdentity} onContextStale={onContextStale} detail={detail} modes={modes} remote={remote} onSelectVersion={onSelectVersion} versionActionLabel={versionActionLabel}>
<DetailTabs localPackage={localPackage} key={cacheIdentity ?? `${detail.namespace}/${detail.slug}/${detail.version}`} cacheIdentity={cacheIdentity} onContextStale={onContextStale} detail={detail} modes={modes} remote={remote} onSelectVersion={onSelectVersion} versionActionLabel={versionActionLabel}>
{detail.documentation.state === 'error' ? <div role="alert"><p>当前版本的说明暂时不可读取。</p><button onClick={retry}>重试</button></div>
: <div className="astron-sh-markdown"><ReactMarkdown rehypePlugins={[rehypeSanitize]} skipHtml components={{
img: ({ alt }) => <span>{alt ? `[图片:${alt}]` : '[图片]'}</span>,

View file

@ -12,8 +12,8 @@ import { readCacheOptions } from './read-cache.js';
type Remote = TypertRemoteNamespaceMap['skillhub'];
type Tab = 'details' | 'versions' | 'securityAudit' | 'reviews';
const names: Record<Tab, string> = { 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<Tab>(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 <Card className="astron-sh-reading-card"><Tabs value={active} onValueChange={value => setSelected(value as Tab)}>
<TabsList aria-label="技能详情">{visible.map(tab => <TabsTrigger key={tab} value={tab}>{names[tab]}</TabsTrigger>)}</TabsList>
{visible.map(tab => <TabsContent key={tab} value={tab}>
{active !== tab ? null : tab === 'details' ? <><div className="astron-sh-reading-body">{children}</div><footer className="astron-sh-panel-footer"><span>SKILL.md</span><span>当前版本 {detail.version}</span></footer></> : tab === 'securityAudit' ? <><div className="astron-sh-reading-body astron-sh-audit-empty"><Icon name="info" /><h3>当前来源未提供公开审核信息</h3><p>当前来源的审核信息不支持匿名读取。</p><p>请检查技能内容与来源,不能据此判断技能已通过安全审核。</p></div><footer className="astron-sh-panel-footer">审核状态取决于当前来源提供的信息</footer></>
{active !== tab ? null : tab === 'details' ? <><div className="astron-sh-reading-body">{children}</div><footer className="astron-sh-panel-footer"><span>SKILL.md</span>{!localPackage && <span>当前版本 {detail.version}</span>}</footer></> : tab === 'securityAudit' ? <><div className="astron-sh-reading-body astron-sh-audit-empty"><Icon name="info" /><h3>当前来源未提供公开审核信息</h3><p>当前来源的审核信息不支持匿名读取。</p><p>请检查技能内容与来源,不能据此判断技能已通过安全审核。</p></div><footer className="astron-sh-panel-footer">审核状态取决于当前来源提供的信息</footer></>
: <>
<ModulePage key={`${identity}/${tab}`} cacheIdentity={identity} page={pages[tab]} setPage={page => setPages(previous => ({ ...previous, [tab]: page }))} onContextStale={onContextStale} tab={tab} token={detail.detailToken} remote={remote} detail={detail} onSelectVersion={onSelectVersion} versionActionLabel={versionActionLabel} /></>}
</TabsContent>)}

View file

@ -193,6 +193,7 @@ export async function apply(ctx: Context): Promise<() => Promise<void>> {
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<void>> {
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('当前会话已关闭,请重新打开会话。');

View file

@ -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 <CardDescription className="skillhub-installed-version" title={identity.sourceKind === 'local-import' ? versions.title : `@${identity.namespace}/${identity.slug} · ${versions.title}`}>
{identity.sourceKind === 'local-import' ? versions.label : `${versions.label} · @${identity.namespace}/${identity.slug}`}
</CardDescription>;
}

View file

@ -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<string, UpdateResult>, 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<string, Updat
}
return badges;
}
export function installedCardVersions(items: Item[]) {
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 installedUpdateKeys(inventory: Item[], results: Record<string, UpdateResult>, 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
<Button variant="ghost" onClick={() => { setChangeIntent(undefined); setSelected(null); }}>← 返回已安装</Button>
<div className="astron-sh-detail-heading"><SkillAvatar slug={selected.slug} namespace={selected.namespace} /><h2 ref={heading} tabIndex={-1}>{selected.slug}</h2><SkillWebsiteLink webUrl={detail.data?.content.state === 'ready' ? detail.data.content.detail.webUrl : undefined}
enabled={detailVerified && detail.data?.content.state === 'ready' && detail.data.content.detail.namespace === selected.namespace && detail.data.content.detail.slug === selected.slug} /></div>
<p>@{selected.namespace}/{selected.slug} · 文档版本 {selected.version}</p>
<p>{selected.sourceKind === 'local-import' ? '本地导入' : `@${selected.namespace}/${selected.slug} · 文档版本 ${selected.version}`}</p>
<div className="astron-sh-detail-layout"><article className="astron-sh-detail-main astron-sh-documentation">{changeIntent && services.changes ? <ChangePreview key={`${contextKey}:${selected.itemKey}:${changeIntent.upgrade}`} services={{ ...services, changes: services.changes }} revision={sourceRevision} itemKey={selected.itemKey} installationKey={JSON.stringify([selected.registry, selected.namespace, selected.slug, selected.scope])} upgrade={changeIntent.upgrade} targetVersion={changeIntent.version} onCompleted={() => { 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 ? <p role="status">正在读取技能说明…</p>
: detail.isError ? <p role="alert">{detail.error.message}</p>
: detail.data.content.state === 'local-only' ? <p role="status">{selected.currentSource === false ? '此技能来自其他来源,可在右侧管理本地安装。' : '远端说明暂不可用,可在管理安装中查看本地状态。'}</p>
: <DetailContent detail={detail.data.content.detail} modes={modes} remote={remote} retry={() => { 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' ? <p role="status">{selected.sourceKind === 'local-import' ? '本地技能文件暂不可读取,请核对安装状态。' : selected.currentSource === false ? '此技能来自其他来源,可在右侧管理本地安装。' : '远端说明暂不可用,可在管理安装中查看本地状态。'}</p>
: <DetailContent localPackage={selected.sourceKind === 'local-import'} detail={detail.data.content.detail} modes={modes} remote={remote} retry={() => { void detail.refetch(); }} cacheIdentity={JSON.stringify([services.sessionId, sourceRevision, selected.namespace, selected.slug, detail.data.content.detail.version])} onContextStale={() => { void detail.refetch(); }} />}</>}
</article><aside className="astron-sh-detail-aside">{management && <InstallationManagement identity={selected} primaryAction={!changeIntent ? actions(records(selected), '使用技能') : undefined} revision={sourceRevision} services={management} updateChecks={Object.fromEntries(Object.entries(results).filter((entry): entry is [string, InstalledUpdateCheck] => entry[1].state !== 'failed'))} useSkill={services.skillUse} onInstall={onInstall && selected.currentSource !== false ? () => onInstall(selected) : undefined} />}</aside></div>
</section>;
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 <section className="skillhub-installed skillhub-controls" aria-label="已安装技能">
<InstalledStyles />
<div className="skillhub-installed-toolbar"><label className="skillhub-installed-search">
<div className="skillhub-installed-toolbar">{services.packages && <PackageImport transfer={services.packages} revision={sourceRevision} contextKey={contextKey} services={services} onCompleted={() => { void query.refetch(); }} />}<label className="skillhub-installed-search">
<input type="search" aria-label="过滤已安装技能" placeholder="搜索已安装技能" value={keyword} onChange={event => setKeyword(event.target.value)} />
</label><Button ref={refreshButton} onClick={() => { void query.refetch(); }} disabled={query.isFetching}>刷新已安装</Button>
{keyword && <Button variant="ghost" onClick={() => setKeyword('')}>清空过滤</Button>}
@ -206,7 +206,6 @@ export function InstalledSkills({ services, sourceRevision, source, remote, mode
const key = JSON.stringify([identity.registry, identity.namespace, identity.slug]);
const presentation = items.find(item => item.summary) ?? identity;
const displayName = presentation.displayName || identity.slug;
const versions = installedCardVersions(items);
const usable = verified && services.management?.selectSkillUse && items.some(item => item.state === 'present' && item.installationState !== 'disabled');
return <Card className="astron-sh-installed-card" key={key}>
<button type="button" className="astron-sh-card-open" aria-label={`查看 ${displayName} @${identity.namespace}/${identity.slug} 详情`}
@ -219,7 +218,7 @@ export function InstalledSkills({ services, sourceRevision, source, remote, mode
<CardHeader className="skillhub-installed-identity">
<CardTitle title={displayName}>{displayName}</CardTitle>
<p className="skillhub-installed-description" title={presentation.summary}>{presentation.summary || '暂无摘要'}</p>
<CardDescription className="skillhub-installed-version" title={`@${identity.namespace}/${identity.slug} · ${versions.title}`}>{versions.label} · @{identity.namespace}/{identity.slug}</CardDescription>
<InstalledCardMetadata items={items} />
</CardHeader>
<div className="skillhub-installed-side">
<div className="skillhub-installed-badges">{installedCardBadges(items, results, verified).map(badge =>

View file

@ -2,7 +2,7 @@ import { z } from 'zod';
const text = z.string().min(1).max(2048);
const item = z.object({ itemKey: text, namespace: text, slug: text, version: text,
scope: z.enum(['user', 'project']), registry: text.optional(), currentSource: z.boolean().optional(), locationKey: text.optional(), installationState: z.enum(['enabled', 'disabled']).optional(), state: z.enum(['present', 'missing', 'metadata-invalid', 'mismatch', 'unreadable']) });
sourceKind: z.literal('local-import').optional(), scope: z.enum(['user', 'project']), registry: text.optional(), currentSource: z.boolean().optional(), locationKey: text.optional(), installationState: z.enum(['enabled', 'disabled']).optional(), state: z.enum(['present', 'missing', 'metadata-invalid', 'mismatch', 'unreadable']) });
const base = { schemaVersion: z.literal(1), toolCallId: text, sourceRevision: text, sourceLabel: text };
const installed = z.object({ ...base, kind: z.literal('skillhub-installed'), items: z.array(item),
complete: z.boolean(), issues: z.array(z.string()), unavailable: z.array(z.enum(['user', 'project'])) });

View file

@ -1,3 +1,4 @@
import { packageDownload } from './package-transfer.js';
import { ManagementNoticeBoundary, useManagementNotice } from './management-notice.js';
import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
import { createContext, useEffect, useContext, useId, useMemo, useRef, useState, type ReactNode } from 'react';
@ -20,6 +21,7 @@ export interface ManagementViewServices {
client: QueryClient;
installation: InstallationServices;
refreshInstalled(signal: AbortSignal): Promise<{ sourceRevision: string; list: InstalledSkillList }>;
exportPackage?(revision: string, itemKey: string, signal: AbortSignal): Promise<RemoteResult<{ filename: string; base64: string }>>;
availability?(revision: string, itemKey: string, signal: AbortSignal): Promise<RemoteResult<SkillAvailability>>;
check(revision: string, itemKey: string, signal: AbortSignal): Promise<RemoteResult<InstalledUpdateCheck>>;
begin(revision: string, itemKey: string, action: 'upgrade' | 'uninstall' | 'enable' | 'disable', version: string | null, requestKey: string, signal: AbortSignal): Promise<RemoteResult<ConversationManagementResult>>;
@ -195,7 +197,7 @@ export async function refreshManagementLocation(services: ManagementViewServices
function ManagementGroup({ items, revision, services, verified }: { items: Item[]; revision: string; services: ManagementViewServices; verified: boolean }) {
const identity = items[0]!;
return <article className="astron-sh-management-group" aria-label={`${identity.namespace}/${identity.slug}`}>
<div className="astron-sh-management-name"><strong>{identity.slug}</strong><span>@{identity.namespace}</span>{identity.currentSource === false && <span title={identity.registry}>其他来源</span>}</div>
<div className="astron-sh-management-name"><strong>{identity.slug}</strong><span>@{identity.namespace}</span>{identity.sourceKind === 'local-import' ? <span>本地导入</span> : identity.currentSource === false && <span title={identity.registry}>其他来源</span>}</div>
<span>{skillInstallationSummary(items)}</span>
<SkillPrimaryActions items={items} revision={revision} verified={verified} summaryVisible select={services.selectSkillUse} useSkill={services.installation.skillUse} onManage={services.installation.manageInstalled ? () => services.installation.manageInstalled!(revision, identity) : undefined} />
</article>;
@ -234,8 +236,7 @@ export function ManagementLocations({ items, revision, services, onUsed, onManag
}) {
return <>{!items.length && <p role="status">该技能暂无安装记录。</p>}{items.map(item => {
const label = managementTargetLabel(items, item).replace('当前用户', '所有项目').replace('当前项目', '仅此项目');
return <section key={item.locationKey ?? item.itemKey} className="astron-sh-management-location-row" aria-label={`${label} v${item.version}`}>
<header><h4>{label}</h4><span>v{item.version}</span><span>{item.state === 'present' ? item.installationState === 'disabled' ? '已停用' : '已启用' : '安装待核验'}</span></header>
return <section key={item.locationKey ?? item.itemKey} className="astron-sh-management-location-row" aria-label={`${label}${item.sourceKind === 'local-import' ? '' : ` v${item.version}`}`}>
<ManagementRow key={item.itemKey} item={item} revision={revision} services={services} initialCheck={updateChecks?.[item.itemKey]} grouped targetLabel={label} expanded onUsed={onUsed} onManagement={onManagement} />
</section>;
})}</>;
@ -262,7 +263,7 @@ function RefreshInstalled() {
</div>;
}
function Identity({ item, compact = false, targetLabel }: { item: Item; compact?: boolean; targetLabel?: string }) {
return <div className="astron-sh-management-identity"><strong>@{item.namespace}/{item.slug}</strong>{!compact && <span>v{item.version}</span>}<span className="astron-sh-management-location">{targetLabel ?? scopeLabel(item.scope)}</span></div>;
return <div className="astron-sh-management-identity"><strong>@{item.namespace}/{item.slug}</strong>{!compact && <span>{item.sourceKind === 'local-import' ? '本地技能' : `v${item.version}`}</span>}<span className="astron-sh-management-location">{targetLabel ?? scopeLabel(item.scope)}</span></div>;
}
function ManagementRow({ item, revision, services, initialCheck, checkOnly = false, grouped = false, expanded = false, targetLabel, onPendingMutation, onManagement, onUsed }: {
item: Item; revision: string; services: ManagementViewServices; initialCheck?: InstalledUpdateCheck; checkOnly?: boolean; grouped?: boolean; expanded?: boolean; targetLabel?: string;
@ -270,7 +271,7 @@ function ManagementRow({ item, revision, services, initialCheck, checkOnly = fal
}) {
const [check, setCheck] = useState(initialCheck);
const notify = useManagementNotice();
const noticeTitle = `${targetLabel ?? scopeLabel(item.scope)} · v${item.version}`;
const noticeTitle = `${targetLabel ?? scopeLabel(item.scope)} · ${item.sourceKind === 'local-import' ? '本地技能' : `v${item.version}`}`;
const availabilityId = useId();
const availability = useQuery({ queryKey: ['skillhub-availability', services.installation.sessionId, revision, item.itemKey, availabilityId],
enabled: false, retry: false, gcTime: 0, queryFn: async ({ signal }) => {
@ -288,8 +289,31 @@ function ManagementRow({ item, revision, services, initialCheck, checkOnly = fal
}, [expanded, notify, noticeTitle, availability.dataUpdatedAt, availability.errorUpdatedAt, availability.isFetching, availability.isError, availability.error, availability.data]);
const changes = services.installation.upgrades?.changes;
const localChanges = useQuery({ queryKey: ['skillhub-local-summary', services.installation.sessionId, revision, item.itemKey],
enabled: expanded && item.state === 'present' && !!changes && !!services.openChanges, retry: false, gcTime: 0,
enabled: item.sourceKind !== 'local-import' && expanded && item.state === 'present' && !!changes && !!services.openChanges, retry: false, gcTime: 0,
queryFn: async ({ signal }) => { services.assertCurrent(); const result = read(await changes!.inspect(revision, item.itemKey, signal)); services.assertCurrent(); signal.throwIfAborted(); return result; } });
const exportRequest = useRef<AbortController>();
const exportBusy = useRef(false);
const [exporting, setExporting] = useState(false);
const [exportError, setExportError] = useState('');
useEffect(() => () => exportRequest.current?.abort(), [revision, item.itemKey]);
async function exportSelected() {
if (!services.exportPackage || exportBusy.current) return;
const controller = new AbortController(); exportRequest.current = controller;
exportBusy.current = true; setExporting(true); setExportError('');
try {
await verifyManagementReference(services, revision, item.itemKey, controller.signal);
const result = read(await services.exportPackage(revision, item.itemKey, controller.signal));
controller.signal.throwIfAborted(); services.assertCurrent();
packageDownload(result.base64, result.filename);
notify?.({ title: noticeTitle, success: true, content: <p>技能包已下载。</p> });
} catch (failure) {
if (!controller.signal.aborted) {
const message = stale(failure) ? '安装记录已变化,请刷新后导出。' : '导出失败,请重试。';
setExportError(message);
notify?.({ title: noticeTitle, content: <p>{message}</p> });
}
} finally { exportBusy.current = false; if (!controller.signal.aborted) setExporting(false); }
}
const [moreOpen, setMoreOpen] = useState(false);
const [useError, setUseError] = useState('');
const moreTrigger = useRef<HTMLButtonElement>(null);
@ -325,11 +349,29 @@ function ManagementRow({ item, revision, services, initialCheck, checkOnly = fal
return <article className={checkOnly ? 'astron-sh-management-check' : 'astron-sh-management-row'} aria-label={checkOnly ? '更新检查' : undefined}
onBlur={event => { if (!expanded && !event.currentTarget.contains(event.relatedTarget as Node | null)) setMoreOpen(false); }}
onKeyDown={event => { if (!expanded && event.key === 'Escape' && moreOpen) { event.preventDefault(); setMoreOpen(false); moreTrigger.current?.focus(); } }}>
{expanded && changes && services.openChanges && item.state === 'present' && <div className="astron-sh-local-state">
{expanded && <header className="astron-sh-position-heading"><div className="astron-sh-position-summary"><div className="astron-sh-position-title"><h4>{targetLabel ?? scopeLabel(item.scope)}</h4><Badge variant={item.state !== 'present' ? 'warning' : item.installationState === 'disabled' ? 'neutral' : 'info'}>{item.state === 'present' ? item.installationState === 'disabled' ? '已停用' : '已启用' : '安装待核验'}</Badge></div>{item.sourceKind !== 'local-import' && <span className="astron-sh-position-version">v{item.version}</span>}</div>
{expanded && !checkOnly && <UseSkillButton services={skillUse} revision={revision} itemKey={item.itemKey} onUsed={onUsed} onHandoff={onUsed} onError={setUseError} renderAction={useAction => (
<DropdownMenu.Root modal={false} open={moreOpen} onOpenChange={setMoreOpen}>
<DropdownMenu.Trigger asChild><Button ref={moreTrigger} size="sm" variant="ghost" aria-label={`管理${targetLabel ?? scopeLabel(item.scope)}`} disabled={pending || exporting}>管理<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden="true"><path d="m6 9 6 6 6-6" /></svg></Button></DropdownMenu.Trigger>
<DropdownMenu.Portal container={moreTrigger.current?.closest('dialog') ?? undefined}>
<DropdownMenu.Content className="skillhub-controls astron-sh-position-menu" align="end" sideOffset={4} collisionPadding={8}>
{item.state === 'present' && item.installationState !== 'disabled' && <DropdownMenu.Item disabled={useAction.disabled} onSelect={useAction.run}>使用此位置</DropdownMenu.Item>}
{services.openChanges && item.sourceKind !== 'local-import' && item.state === 'present' && <DropdownMenu.Item onSelect={() => services.openChanges!(item, false, undefined, revision)}>查看本地修改</DropdownMenu.Item>}
{services.exportPackage && item.state === 'present' && <DropdownMenu.Item disabled={exporting || pending} onSelect={() => { void exportSelected(); }}>导出技能包</DropdownMenu.Item>}
{services.availability && <DropdownMenu.Item disabled={availability.isFetching} onSelect={() => { void availability.refetch(); }}>检查可用性</DropdownMenu.Item>}
{item.currentSource !== false && item.state === 'present' && <DropdownMenu.Item onSelect={() => { void run('check'); }}>检查更新</DropdownMenu.Item>}
{item.state === 'present' && <DropdownMenu.Item onSelect={() => { void run(item.installationState === 'disabled' ? 'enable' : 'disable'); }}>{item.installationState === 'disabled' ? '启用' : '停用'}</DropdownMenu.Item>}
{item.state === 'present' && <DropdownMenu.Item onSelect={() => { void run('uninstall'); }}>卸载</DropdownMenu.Item>}
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
)} />}
</header>}
{item.sourceKind !== 'local-import' && expanded && changes && services.openChanges && item.state === 'present' && <div className="astron-sh-local-state">
{localChanges.data?.status === 'ready' && localChanges.data.changes.length > 0 && <Button size="sm" variant="ghost" className="astron-sh-local-state-trigger" onClick={() => services.openChanges!(item, false, undefined, revision)}><Badge variant="warning">本地修改 · {localChanges.data.changes.length}</Badge></Button>}
{(localChanges.isError || localChanges.data?.status === 'blocked') && <span className="astron-sh-local-state-unknown">本地状态未确认 <Button size="sm" variant="ghost" aria-label={`重新检查${targetLabel ?? scopeLabel(item.scope)}的本地修改`} disabled={localChanges.isFetching} onClick={() => void localChanges.refetch()}>重试</Button></span>}
</div>}
{!expanded && (grouped ? <span className="astron-sh-management-version">{targetLabel && `${targetLabel} · `}{check?.state !== 'upgradable' && `v${item.version}`}</span> : <Identity item={item} compact={checkOnly && check?.state === 'upgradable'} />)}
{!expanded && (grouped ? <span className="astron-sh-management-version">{targetLabel && `${targetLabel} · `}{check?.state !== 'upgradable' && (item.sourceKind === 'local-import' ? '本地技能' : `v${item.version}`)}</span> : <Identity item={item} compact={checkOnly && check?.state === 'upgradable'} />)}
{error ? <><p role="alert">{error}</p><RefreshInstalled /></> : <>
{!expanded && item.installationState === 'disabled' && <span role="status">已停用</span>}
{item.state !== 'present' && <p role="alert">{item.state === 'missing' ? '安装文件缺失' : '安装记录待核验'}</p>}
@ -339,26 +381,12 @@ function ManagementRow({ item, revision, services, initialCheck, checkOnly = fal
<div className="astron-sh-management-actions">
{check?.state === 'upgradable' && <Button size="sm" variant={expanded ? 'outline' : 'default'} disabled={pending} onClick={() => void run('upgrade')}>更新</Button>}
{!expanded && check?.state === 'unavailable' && <Button size="sm" variant="ghost" disabled={pending} onClick={() => void run('check')}>{pending ? '检查中…' : '重试检查'}</Button>}
{!checkOnly && item.state === 'present' && item.installationState === 'disabled' && <Button size="sm" disabled={pending} onClick={() => void run('enable')}>启用</Button>}
{!expanded && !checkOnly && item.state === 'present' && item.installationState === 'disabled' && <Button size="sm" disabled={pending} onClick={() => void run('enable')}>启用</Button>}
{!expanded && !checkOnly && !check && item.state === 'present' && item.installationState !== 'disabled' && <UseSkillButton services={skillUse} revision={revision} itemKey={item.itemKey} onUsed={onUsed} onHandoff={onUsed} label={expanded ? '使用此位置' : '使用此技能'} onError={setUseError} />}
{expanded && !checkOnly && <UseSkillButton services={skillUse} revision={revision} itemKey={item.itemKey} onUsed={onUsed} onHandoff={onUsed} onError={setUseError} renderAction={useAction => (
<DropdownMenu.Root modal={false} open={moreOpen} onOpenChange={setMoreOpen}>
<DropdownMenu.Trigger asChild><Button ref={moreTrigger} size="sm" variant="ghost" aria-label="更多操作" disabled={pending}>···</Button></DropdownMenu.Trigger>
<DropdownMenu.Portal container={moreTrigger.current?.closest('dialog') ?? undefined}>
<DropdownMenu.Content className="skillhub-controls astron-sh-position-menu" align="end" sideOffset={4} collisionPadding={8}>
{item.state === 'present' && item.installationState !== 'disabled' && <DropdownMenu.Item disabled={useAction.disabled} onSelect={useAction.run}>使用此位置</DropdownMenu.Item>}
{services.openChanges && item.state === 'present' && <DropdownMenu.Item onSelect={() => services.openChanges!(item, false, undefined, revision)}>查看本地修改</DropdownMenu.Item>}
{services.availability && <DropdownMenu.Item disabled={availability.isFetching} onSelect={() => { void availability.refetch(); }}>检查可用性</DropdownMenu.Item>}
{item.currentSource !== false && item.state === 'present' && <DropdownMenu.Item onSelect={() => { void run('check'); }}>检查更新</DropdownMenu.Item>}
{item.state === 'present' && item.installationState !== 'disabled' && <DropdownMenu.Item onSelect={() => { void run('disable'); }}>停用</DropdownMenu.Item>}
{item.state === 'present' && <DropdownMenu.Item onSelect={() => { void run('uninstall'); }}>卸载</DropdownMenu.Item>}
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
)} />}
{!expanded && !checkOnly && (services.availability || item.state === 'present') && <Button ref={moreTrigger} size="sm" variant="ghost" className="astron-sh-management-more-trigger" aria-label="更多操作" aria-expanded={moreOpen} disabled={pending} onClick={() => setMoreOpen(value => !value)}>···</Button>}
{!checkOnly && item.state === 'missing' && <Button size="sm" disabled={pending} onClick={() => void run('uninstall')}>清理记录</Button>}
</div>
{!notify && exportError && <p role="alert">{exportError}</p>}
{useError && <p className="astron-sh-management-use-error" role="alert">{useError}</p>}
{(!expanded || !notify || (availability.isError && stale(availability.error))) && (availability.isFetching ? <p role="status">正在检查可用性…</p> : availability.isError ? <><p role="alert">{stale(availability.error) ? '安装记录已变化,请重新查询。' : '可用性暂时无法核验。'}</p>{stale(availability.error) && <RefreshInstalled />}</> : availability.data && <AvailabilityResult value={availability.data} />)}
{!expanded && moreOpen && <div className="astron-sh-management-more-content" aria-label="技能操作">
@ -392,8 +420,8 @@ export function ManagementConfirmation({ initial, services, onCancelled, onCompl
useEffect(() => { if (completed && toggle && operation.data?.warningCount === 0 && !operation.data.resultDetails?.warnings.length && !['incomplete', 'unknown'].includes(operation.data.recovery)) onCompleted?.(); }, [completed, toggle, onCompleted, operation.data]);
const warned = (operation.data?.warningCount ?? 0) > 0 || !!operation.data?.resultDetails?.warnings.length;
const recoveryPending = !!operation.data && ['incomplete', 'unknown'].includes(operation.data.recovery);
return <article className={`astron-sh-management-receipt ${completed ? 'is-complete' : ''}`} aria-label={`${verb}技能`}>{presentation === 'dialog' && toggle ? <div className="astron-sh-toggle-identity"><strong>{title || result.item.slug}</strong><span>@{result.item.namespace}/{result.item.slug} · v{result.item.version}</span><span className="astron-sh-toggle-scope">{result.item.scope === 'user' ? '所有项目 · 当前用户' : '仅此项目'}</span></div> : <Identity item={result.item} compact targetLabel={targetLabel} />}
{!(presentation === 'dialog' && toggle) && <p className="astron-sh-management-version">v{result.item.version}{result.action === 'upgrade' && result.candidateVersion ? ` → v${result.candidateVersion}` : ''}</p>}
return <article className={`astron-sh-management-receipt ${completed ? 'is-complete' : ''}`} aria-label={`${verb}技能`}>{presentation === 'dialog' && toggle ? <div className="astron-sh-toggle-identity"><strong>{title || result.item.slug}</strong><span>@{result.item.namespace}/{result.item.slug} · {result.item.sourceKind === 'local-import' ? '本地技能' : `v${result.item.version}`}</span><span className="astron-sh-toggle-scope">{result.item.scope === 'user' ? '所有项目 · 当前用户' : '仅此项目'}</span></div> : <Identity item={result.item} compact targetLabel={targetLabel} />}
{!(presentation === 'dialog' && toggle) && <p className="astron-sh-management-version">{result.item.sourceKind === 'local-import' ? '本地技能' : `v${result.item.version}`}{result.action === 'upgrade' && result.candidateVersion ? ` → v${result.candidateVersion}` : ''}</p>}
{expired ? <><p role="alert">{error}</p><RefreshInstalled /></> : <>
{toggle && result.status === 'awaiting-confirmation' && <p>{result.action === 'disable' ? '仅停用此位置,不撤回已加载内容;其他同名安装可能仍可用。' : '仅恢复此位置,保留原有调用权限。'}</p>}
{result.status === 'awaiting-confirmation' && (error ? <><p role="alert">{error}</p><Button size="sm" disabled={pending} onClick={() => void confirm(decision.current)}>重试原请求</Button></> : <>{!(presentation === 'dialog' && toggle) && <p>确认{verb}这份安装?{result.item.scope === 'user' ? '影响当前用户的多个项目。' : '仅影响当前项目。'}</p>}

View file

@ -101,6 +101,21 @@ export function NativeControlStyles() {
.astron-sh-modal-layer{position:relative;z-index:1000}
.skillhub-controls .astron-sh-dialog-overlay{position:fixed;inset:0;z-index:1000;background:color-mix(in srgb,#000 40%,transparent)}
.skillhub-controls .astron-sh-dialog{position:fixed;z-index:1001;top:50%;left:50%;transform:translate(-50%,-50%);width:min(460px,calc(100vw - 32px));max-height:calc(100dvh - 32px);overflow:auto;border:1px solid var(--astron-sh-border);border-radius:12px;padding:24px;background:var(--astron-sh-bg);color:var(--astron-sh-fg);box-shadow:0 16px 60px #0003}
.skillhub-controls .astron-sh-dialog.astron-sh-package-dialog{display:flex;flex-direction:column;gap:12px;overflow:visible;box-sizing:border-box;max-height:calc(100dvh - 32px);padding:20px}
.skillhub-controls .astron-sh-package-dialog>h2,.skillhub-controls .astron-sh-package-dialog>p{flex:none;margin:0}
.skillhub-controls .astron-sh-package-body{min-height:0;min-width:0;overflow:auto;overscroll-behavior:contain;overflow-wrap:anywhere}
.skillhub-controls .astron-sh-package-preview{min-width:0;display:grid;gap:10px}
.skillhub-controls .astron-sh-package-name{display:block;overflow-wrap:anywhere;font-size:15px;line-height:1.5}
.skillhub-controls .astron-sh-package-summary{max-height:120px;overflow:auto;overscroll-behavior:contain;overflow-wrap:anywhere;white-space:pre-wrap;font-size:14px;line-height:1.6;color:var(--astron-sh-muted);padding-right:4px}
.skillhub-controls .astron-sh-package-summary:focus-visible{outline:2px solid var(--astron-sh-accent);outline-offset:-2px;border-radius:3px}
.skillhub-controls .astron-sh-package-dialog .astron-sh-package-count{margin:0;font-size:12px}
.skillhub-controls .astron-sh-package-result{box-sizing:border-box;flex:none;min-height:132px;margin-top:0;padding:14px;border:1px solid var(--astron-sh-border);border-radius:8px;background:var(--astron-sh-soft)}
.skillhub-controls .astron-sh-package-result>strong{font-size:14px}
.skillhub-controls .astron-sh-package-result-action{min-height:32px;margin-top:14px}
.skillhub-controls .astron-sh-package-scope{flex:none;min-width:0}
.skillhub-controls .astron-sh-package-dialog>.astron-sh-dialog-actions{flex:none;margin-top:4px}
@media(max-width:640px){.skillhub-controls .astron-sh-package-summary{max-height:96px}.skillhub-controls .astron-sh-dialog.astron-sh-package-dialog{padding:18px}}
.skillhub-controls .astron-sh-dialog h2{font-size:18px}.skillhub-controls .astron-sh-dialog p{font-size:14px;color:var(--astron-sh-muted)}.skillhub-controls .astron-sh-dialog dl{font-size:13px;padding:14px;background:var(--astron-sh-soft);border-radius:7px;overflow-wrap:anywhere}.skillhub-controls .astron-sh-dialog dt{color:var(--astron-sh-muted)}.skillhub-controls .astron-sh-dialog dd{margin:0 0 8px}.skillhub-controls .astron-sh-dialog-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:20px}
.skillhub-controls .astron-sh-install-panel .astron-sh-scope-help{font-size:12px;line-height:1.5;margin:7px 0 16px;color:var(--astron-sh-muted)}
.skillhub-controls .astron-sh-current-install{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px;border:1px solid var(--astron-sh-border);border-radius:8px;background:var(--astron-sh-bg);margin:12px 0}
@ -236,11 +251,17 @@ export function NativeControlStyles() {
.skillhub-controls .astron-sh-confirm-close{position:absolute;right:14px;top:14px}
.skillhub-controls .astron-sh-detail-aside{align-self:start;position:sticky;top:16px}
.astron-sh-detail-drawer{container-type:inline-size}
@container(max-width:680px){.skillhub-controls .astron-sh-detail-aside{position:static;order:-1}.skillhub-controls .astron-sh-install-management{max-height:60dvh}}
.skillhub-controls .astron-sh-management-location-row{border:1px solid var(--astron-sh-border);border-radius:8px;padding:12px;margin:10px 0;background:var(--astron-sh-bg)}
.skillhub-controls .astron-sh-management-location-row header{display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px;font-size:12px;color:var(--astron-sh-muted)}
.skillhub-controls .astron-sh-management-location-row h4{font-size:13px;margin:0;color:var(--astron-sh-fg)}
@container(max-width:680px){.skillhub-controls .astron-sh-detail-aside{position:static;order:-1;align-self:stretch;width:100%}.skillhub-controls .astron-sh-install-management{max-height:60dvh}}
.skillhub-controls .astron-sh-management-location-row{padding:14px 0;margin:0;border-top:1px solid var(--astron-sh-border);min-width:0}
.skillhub-controls .astron-sh-position-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;width:100%;min-width:0}
.skillhub-controls .astron-sh-position-summary{min-width:0;display:grid;gap:4px}
.skillhub-controls .astron-sh-position-title{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
.skillhub-controls .astron-sh-position-title h4{font-size:13px;font-weight:600;margin:0;color:var(--astron-sh-fg)}
.skillhub-controls .astron-sh-position-title .astron-sh-badge{font-size:11px;line-height:18px;padding:0 6px}
.skillhub-controls .astron-sh-position-version{font-size:12px;color:var(--astron-sh-muted)}
.skillhub-controls .astron-sh-position-heading>.astron-sh-button{flex-shrink:0;display:inline-flex;align-items:center;gap:6px}
.skillhub-controls .astron-sh-management-location-row .astron-sh-button{font-size:12px;min-height:28px;height:28px;padding:3px 8px}
.skillhub-controls .astron-sh-management-location-row .astron-sh-management-actions,.skillhub-controls .astron-sh-management-location-row .astron-sh-management-more-content{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px}
.skillhub-controls .astron-sh-management-location-row .astron-sh-management-actions:empty{display:none}
.skillhub-controls .astron-sh-management-location-row .astron-sh-management-more-content{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px}
`}</style>;
}

View file

@ -0,0 +1,139 @@
import { useQuery } from '@tanstack/react-query';
import { exactInstalledSkill, UseSkillButton, type SkillUseServices } from './use-skill.js';
import { useEffect, useRef, useState } from 'react';
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol';
import type { InstalledSkillList, NativeOperation } from '../host/types.js';
import { Button, Dialog, DialogContent, DialogTitle, DialogDescription, SelectField } from './ui.js';
import { useInstallationOperation } from './use-installation-operation.js';
export const MAX_TRANSFER_BYTES = 8 * 1024 * 1024;
export interface PackagePreview { previewId: string; name: string; summary?: string; files: number; bytes: number; expiresAt: string }
export interface PackageTransferServices {
preview(revision: string, base64: string, signal: AbortSignal): Promise<RemoteResult<PackagePreview>>;
confirm(revision: string, preview: string, scope: 'user' | 'project', requestKey: string, signal: AbortSignal): Promise<RemoteResult<NativeOperation | null>>;
}
export function encodePackage(bytes: Uint8Array): string {
if (!bytes.length || bytes.length > MAX_TRANSFER_BYTES) throw new Error('请选择不超过 8 MB 的 ZIP 技能包。');
let text = '';
for (let start = 0; start < bytes.length; start += 16384) text += String.fromCharCode(...bytes.subarray(start, start + 16384));
return btoa(text);
}
export function packageDownload(base64: string, filename: string): void {
const text = atob(base64);
if (!text.length || text.length > MAX_TRANSFER_BYTES) throw new Error('导出文件超过传输限制。');
const bytes = Uint8Array.from(text, char => char.charCodeAt(0));
const url = URL.createObjectURL(new Blob([bytes], { type: 'application/zip' }));
const link = document.createElement('a');
link.href = url; link.download = filename.replace(/[\\/]/g, '_');
document.body.append(link); link.click(); link.remove();
// Give the browser time to begin consuming the download before releasing it.
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
export function PackagePreviewContent({ preview }: { preview: PackagePreview }) {
return <section className="astron-sh-package-preview" aria-label="技能包预览">
<strong className="astron-sh-package-name">{preview.name}</strong>
{preview.summary && <div className="astron-sh-package-summary" role="region" aria-label="技能说明" tabIndex={0}>{preview.summary}</div>}
<p className="astron-sh-package-count">{preview.files} 个文件 · {(preview.bytes / 1024).toFixed(1)} KB</p>
</section>;
}
export function importProgressView(operation: Pick<NativeOperation, 'phase' | 'warningCount' | 'recovery' | 'resultDetails'> | undefined, confirming: boolean, readFailed: boolean) {
if (readFailed) return { label: '导入状态待核验', state: 'stopped' as const };
if (!operation) return { label: confirming ? '正在确认导入' : '等待确认导入', state: confirming ? 'running' as const : 'ready' as const };
if (operation.phase === 'completed') {
if (['incomplete', 'unknown'].includes(operation.recovery ?? '')) return { label: '导入结果待核验', state: 'stopped' as const };
const warning = operation.warningCount > 0 || !!operation.resultDetails?.warnings.length;
return { label: warning ? '导入完成,需核验告警' : '导入成功', state: 'complete' as const };
}
if (['failed', 'unknown', 'recovery-required'].includes(operation.phase)) return { label: operation.phase === 'failed' ? '导入未完成' : '导入状态待核验', state: 'stopped' as const };
const labels = { accepted: '准备导入', staging: '正在校验技能包', revalidating: '正在核验安装位置', committing: '正在写入技能', recovering: '正在恢复核验' };
return { label: labels[operation.phase as keyof typeof labels] ?? '正在导入', state: 'running' as const };
}
export function PackageImport({ transfer, revision, contextKey, services, onCompleted }: {
transfer: PackageTransferServices; revision: string; contextKey: string;
services: { sessionId: string; skillUse?: SkillUseServices; list?(revision: string, signal: AbortSignal): Promise<RemoteResult<InstalledSkillList>>; operation(id: string, host: string): Promise<RemoteResult<NativeOperation | null>> }; onCompleted(): void;
}) {
const [container, setContainer] = useState<HTMLSpanElement | null>(null);
const [open, setOpen] = useState(false);
const [preview, setPreview] = useState<PackagePreview>();
const [scope, setScope] = useState<'user' | 'project'>('project');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [accepted, setAccepted] = useState<NativeOperation>();
const request = useRef<AbortController>();
const requestKey = useRef('');
const confirming = useRef(false);
const file = useRef<HTMLInputElement>(null);
const trigger = useRef<HTMLButtonElement>(null);
const receipt = useInstallationOperation(services, accepted?.context.hostInstanceId ?? '', accepted?.operationId);
const operation = receipt.data ?? accepted;
const progress = importProgressView(operation, busy && !!preview, receipt.isError || receipt.data === null);
const installed = useQuery({ queryKey: ['skillhub-import-result', contextKey, operation?.operationId],
enabled: progress.state === 'complete' && !!services.list, retry: false,
queryFn: async ({ signal }) => {
const response = await services.list!(revision, signal);
signal.throwIfAborted();
if (!response.ok || operation?.context.sourceIdentity !== 'local:import' || operation.namespace !== 'local' || operation.slug !== preview?.name) throw new Error('无法核验导入记录。');
const match = exactInstalledSkill(response.value, { registry: 'local:import', namespace: 'local', slug: operation.slug, version: 'local', scope });
return match?.sourceKind === 'local-import' ? match : null;
} });
useEffect(() => () => request.current?.abort(), [contextKey]);
useEffect(() => {
request.current?.abort(); setOpen(false); setPreview(undefined); setAccepted(undefined); setBusy(false); setError('');
}, [contextKey]);
useEffect(() => { if (receipt.data?.phase === 'completed') onCompleted(); }, [receipt.data?.phase]);
async function choose(selected: File) {
request.current?.abort();
const controller = new AbortController(); request.current = controller;
setOpen(true); setBusy(true); setError(''); setPreview(undefined); setAccepted(undefined); setScope('project');
try {
if (!selected.name.toLowerCase().endsWith('.zip') || selected.size > MAX_TRANSFER_BYTES) throw new Error('请选择不超过 8 MB 的 ZIP 技能包。');
const bytes = new Uint8Array(await selected.arrayBuffer()); controller.signal.throwIfAborted();
const response = await transfer.preview(revision, encodePackage(bytes), controller.signal);
controller.signal.throwIfAborted();
if (!response.ok) throw new Error('无法读取技能包,请检查包格式或重新选择。');
setPreview(response.value); requestKey.current = crypto.randomUUID();
} catch (failure) { if (!controller.signal.aborted) setError(failure instanceof Error ? failure.message : '无法读取技能包。'); }
finally { if (!controller.signal.aborted) setBusy(false); }
}
async function confirm() {
if (!preview || busy || accepted || confirming.current) return;
confirming.current = true;
const controller = new AbortController(); request.current = controller; setBusy(true); setError('');
try {
const response = await transfer.confirm(revision, preview.previewId, scope, requestKey.current, controller.signal);
controller.signal.throwIfAborted();
if (!response.ok || !response.value) throw new Error('未能确认导入,请检查安装位置是否已有同名技能或预览是否过期。');
setAccepted(response.value);
} catch (failure) { if (!controller.signal.aborted) setError(failure instanceof Error ? failure.message : '导入未确认。'); }
finally { confirming.current = false; if (!controller.signal.aborted) setBusy(false); }
}
return <span ref={setContainer}>
<input ref={file} type="file" accept=".zip,application/zip" aria-label="选择技能 ZIP" hidden onChange={event => { const selected = event.target.files?.[0]; event.target.value = ''; if (selected) void choose(selected); }} />
<Button ref={trigger} disabled={!!accepted && !['completed', 'failed', 'recovery-required', 'unknown'].includes(operation?.phase ?? '')} onClick={() => file.current?.click()}>导入技能包</Button>
<Dialog open={open} onOpenChange={next => { if (!next) { request.current?.abort(); setBusy(false); } setOpen(next); }}><DialogContent container={container} className="astron-sh-dialog astron-sh-package-dialog" onCloseAutoFocus={event => {
event.preventDefault();
if (trigger.current && !trigger.current.disabled) trigger.current.focus();
else trigger.current?.closest('.skillhub-installed-toolbar')?.querySelector<HTMLInputElement>('input[type=search]')?.focus();
}}>
<DialogTitle>导入技能包</DialogTitle><DialogDescription>安装到本机,不上传到技能市场。</DialogDescription>
<div className="astron-sh-package-body">
{preview && <PackagePreviewContent preview={preview} />}
{busy && !preview && <p role="status">正在检查技能包…</p>}
{(error || receipt.isError) && <p role="alert">{error || '暂时无法查询导入状态,请关闭后刷新已安装。'}</p>}
</div>
{preview && <div className="astron-sh-package-scope"><SelectField label="安装范围" value={scope} onValueChange={value => setScope(value as 'user' | 'project')} disabled={busy || !!accepted} options={[{ value: 'project', label: '仅此项目' }, { value: 'user', label: '所有项目' }]} /></div>}
{preview && <section className="astron-sh-package-result" aria-label="导入结果" data-state={progress.state}>
<strong role={progress.state === 'stopped' ? 'alert' : 'status'}>{progress.label}</strong>
{progress.state !== 'ready' && <div className="astron-sh-install-progress-track" data-state={progress.state} role="progressbar" aria-label="导入进度" aria-valuemin={0} aria-valuemax={100} aria-valuenow={progress.state === 'complete' ? 100 : undefined} aria-valuetext={progress.label}><span /></div>}
<div className="astron-sh-package-result-action">{progress.state === 'stopped' && <p>请在已安装中核对当前状态。</p>}{progress.state === 'complete' && (installed.isError || installed.data === null) && <p>安装记录暂未确认,请在已安装中核对。</p>}{progress.state === 'complete' && installed.data && services.skillUse && <UseSkillButton services={services.skillUse} revision={revision} label="使用技能" resolve={async signal => {
const inventory = await services.list!(revision, signal);
if (!inventory.ok) throw new Error('无法核验导入记录,请刷新已安装。');
const exact = exactInstalledSkill(inventory.value, { registry: 'local:import', namespace: 'local', slug: operation!.slug, version: 'local', scope });
if (exact?.sourceKind !== 'local-import') throw new Error('导入记录已变化,请刷新已安装。');
return exact.itemKey;
}} onUsed={() => setOpen(false)} onHandoff={() => setOpen(false)} onError={setError} />}</div>
</section>}
<div className="astron-sh-dialog-actions"><Button onClick={() => { request.current?.abort(); setBusy(false); setOpen(false); }}>关闭</Button>{preview && !accepted && <Button variant="default" disabled={busy} onClick={() => { void confirm(); }}>确认导入</Button>}</div>
</DialogContent></Dialog>
</span>;
}

View file

@ -1,3 +1,6 @@
import { readFile } from 'node:fs/promises';
import { parseDocument } from 'yaml';
import type { PackageImportPreview, PackageExport } from './types.js';
import { installationContextError } from './installation-context.js';
import type { InstallationContextReason } from './installation-context.js';
import { Context, symbols } from '@deepseek-ai/cordis';
@ -74,6 +77,8 @@ export class SkillHubService extends TypertRemoteService {
private readonly installationTargets = new InstallationTargets();
private readonly upgradePlans = new UpgradePlans();
private readonly changeBackups = new Map<string, Promise<VerifiedBackupReceipt>>();
private readonly packageImports = new ConfirmationPlans<{ archive: Uint8Array; name: string; fingerprint: string; hostInstanceId: string }>();
private packagePreviewBytes = 0;
private readonly changes = new ConfirmationPlans<{ itemKey: string; local: Extract<LocalChangesSnapshot, {status: 'ready'}>; version?: VersionChangesSnapshot; backup?: VerifiedBackupReceipt }>();
private readonly resets = new ConfirmationPlans<{ itemKey: string; snapshot: Extract<LocalChangesSnapshot, {status: 'ready'}>; paths: string[] }>();
private readonly removalPlans = new RemovalPlans();
@ -99,7 +104,7 @@ export class SkillHubService extends TypertRemoteService {
void runtime.start();
return async () => {
this.installationTargets.clear();
this.upgradePlans.clear(); this.changes.clear(); this.resets.clear(); this.changeBackups.clear();
this.packageImports.clear(); this.packagePreviewBytes = 0; this.upgradePlans.clear(); this.changes.clear(); this.resets.clear(); this.changeBackups.clear();
this.removalPlans.clear(); this.togglePlans.clear();
if (this.localRuntime === runtime) this.localRuntime = undefined;
await runtime.dispose();
@ -117,7 +122,7 @@ export class SkillHubService extends TypertRemoteService {
ctx.effect(() => registerSearchTool(ctx.tools, (query, context, signal) => this.searchConversation(query, context, signal)));
ctx.effect(() => registerInstallTool(ctx.tools, (request, context, signal) => this.installConversationWithChoice(request, context, signal), reason => { this.installationContextDiagnostic = reason; }));
});
ctx.effect(() => () => { this.lifetime.abort(); for (const scan of this.installedUpdateScans.values()) scan.close(); this.pendingConversationInstalls.clear(); this.pendingConversationChoices.clear(); this.managementRequests.clear(); this.managementConfirmations.clear(); this.details.clear(); this.capabilities.clear(); this.selections.clear(); this.installationTargets.clear(); this.upgradePlans.clear(); this.changes.clear(); this.resets.clear(); this.changeBackups.clear(); this.removalPlans.clear(); this.togglePlans.clear(); });
ctx.effect(() => () => { this.lifetime.abort(); for (const scan of this.installedUpdateScans.values()) scan.close(); this.pendingConversationInstalls.clear(); this.pendingConversationChoices.clear(); this.managementRequests.clear(); this.managementConfirmations.clear(); this.details.clear(); this.capabilities.clear(); this.selections.clear(); this.installationTargets.clear(); this.packageImports.clear(); this.packagePreviewBytes = 0; this.upgradePlans.clear(); this.changes.clear(); this.resets.clear(); this.changeBackups.clear(); this.removalPlans.clear(); this.togglePlans.clear(); });
}
private installationContextDiagnostic?: InstallationContextReason;
@ -147,7 +152,7 @@ export class SkillHubService extends TypertRemoteService {
this.selections.clear();
this.installationTargets.clear();
this.upgradePlans.clear(); this.changes.clear(); this.resets.clear(); this.changeBackups.clear();
this.packageImports.clear(); this.packagePreviewBytes = 0; this.upgradePlans.clear(); this.changes.clear(); this.resets.clear(); this.changeBackups.clear();
this.removalPlans.clear(); this.togglePlans.clear();
this.capabilities.clear();
this.registry = registry;
@ -351,7 +356,7 @@ export class SkillHubService extends TypertRemoteService {
const items = result.items.map((item, index) => {
const itemKey = this.installedItemKey(agent.session.id, cwd, sourceRevision, item);
const locationKey = createHmac('sha256', this.installedReferenceKey).update(JSON.stringify([agent.session.id, cwd, sourceRevision, item.registry, item.namespace, item.slug, item.scope, item.targetPath])).digest('base64url');
return { ...presentation[index], registry: item.registry, currentSource: item.registry === this.getContext().registryUrl.replace(/\/+$/, ''), itemKey, locationKey, installationState: item.installationState, namespace: item.namespace, slug: item.slug, version: item.version, scope: item.scope, state: item.state };
return { ...presentation[index], ...(item.registry === 'local:import' ? { sourceKind: 'local-import' as const } : {}), registry: item.registry, currentSource: item.registry === this.getContext().registryUrl.replace(/\/+$/, ''), itemKey, locationKey, installationState: item.installationState, namespace: item.namespace, slug: item.slug, version: item.version, scope: item.scope, state: item.state };
});
return { items, complete: result.complete, issues: result.issues, unavailable };
}
@ -543,14 +548,123 @@ export class SkillHubService extends TypertRemoteService {
}
}
@RemoteScope('agent')
async previewPackageImport(sourceRevision: string, base64: string, signal: AbortSignal): Promise<PackageImportPreview> {
const context = this.packageContext(sourceRevision);
const combined = AbortSignal.any([signal, this.lifetime.signal]);
if (typeof base64 !== 'string' || base64.length > 11_184_812 || (base64.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(base64))) {
throw new RemoteError('skillhub/invalid-installation-request', '请选择不超过 8 MiB 的 ZIP 技能包。', { retryable: false });
}
const archive = new Uint8Array(Buffer.from(base64, 'base64'));
if (!archive.length || archive.byteLength > 8 * 1024 * 1024 || Buffer.from(archive).toString('base64') !== base64) throw new RemoteError('skillhub/invalid-installation-request', '技能包为空或超过 8 MiB。', { retryable: false });
try {
const preview = await context.runtime.previewPackage(archive, async directory => {
combined.throwIfAborted();
await validateDshSkill(context.agent.ctx, directory, combined);
const content = await readFile(join(directory, 'SKILL.md'), 'utf8');
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(content);
const doc = match ? parseDocument(match[1]!, { uniqueKeys: true }) : undefined;
const value: unknown = doc && !doc.errors.length ? doc.toJS({ maxAliasCount: 20 }) : undefined;
if (!value || typeof value !== 'object' || !('name' in value) || typeof value.name !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value.name) || value.name.length > 128) throw new Error('Invalid skill name');
return { name: value.name, ...('description' in value && typeof value.description === 'string' ? { summary: value.description.slice(0, 1000) } : {}) };
});
combined.throwIfAborted(); context.valid();
// Bound all retained archive bytes; evict previews together instead of retaining unbounded uploads.
if (this.packagePreviewBytes + archive.length > 32 * 1024 * 1024) { this.packageImports.clear(); this.packagePreviewBytes = 0; }
const plan = this.packageImports.issue(context.scope, { archive, name: preview.name, fingerprint: preview.fingerprint, hostInstanceId: context.hostInstanceId });
this.packagePreviewBytes += archive.length;
return { previewId: plan.planId, expiresAt: plan.expiresAt, name: preview.name, summary: preview.summary, files: preview.files, bytes: preview.bytes };
} catch (error) {
combined.throwIfAborted(); context.valid();
if (error instanceof RemoteError) throw error;
throw new RemoteError('skillhub/invalid-installation-request', '技能包无效:请检查根目录 SKILL.md、文件路径及大小限制。', { retryable: false });
}
}
@RemoteScope('agent')
async confirmPackageImport(sourceRevision: string, previewId: string, scope: 'user' | 'project', requestKey: string, signal: AbortSignal): Promise<NativeOperation | null> {
const context = this.packageContext(sourceRevision);
if (!['user', 'project'].includes(scope) || !/^[0-9a-f-]{36}$/i.test(previewId) || !/^[0-9a-f-]{36}$/i.test(requestKey)) throw new RemoteError('skillhub/invalid-installation-request', 'Invalid import request.', { retryable: false });
try {
return await context.runtime.submitPackageImport({ hostInstanceId: context.hostInstanceId, ownerId: context.agent.session.id,
requestKey, mode: 'new', parameters: { previewId, scope } }, async () => {
signal.throwIfAborted(); context.valid();
const snapshot = this.packageImports.claim(previewId, context.scope, requestKey);
if (snapshot.hostInstanceId !== context.hostInstanceId) throw installationContextError('HOST_MISMATCH');
const policy = context.agent.ctx.get('sandboxPolicy')?.resolve({ session: context.agent.session });
const target = await resolveInstallationPath({ scope, cwd: context.scope.cwd, fs: context.fs, policy, signal });
context.valid();
return { archive: snapshot.archive,
acceptance: { kind: 'install', namespace: 'local', slug: snapshot.name, version: 'local', targetLabel: scope === 'user' ? '所有项目' : '仅此项目', targetPaths: [join(target.root, snapshot.name)],
context: { sourceIdentity: 'local:import', sourceLabel: '本地导入', sourceRevision, hostLabel: 'DSH Host', initiatedFrom: 'plaza' } },
execution: { registry: 'local:import', namespace: 'local', slug: snapshot.name, version: 'local', versionId: 1, fingerprint: snapshot.fingerprint,
root: target.root, scope, validateStaged: directory => validateDshSkill(context.agent.ctx, directory, new AbortController().signal),
authorize: async paths => {
context.valid(false);
const currentPolicy = context.agent.ctx.get('sandboxPolicy')?.resolve({ session: context.agent.session });
const current = await resolveInstallationPath({ scope, cwd: context.scope.cwd, fs: context.fs, policy: currentPolicy, signal: this.lifetime.signal });
context.valid(false);
if (current.root !== target.root || current.dshHome !== target.dshHome) throw installationContextError('TARGET');
await assertInstallationMutation(target.root, paths, currentPolicy);
} } };
}) ?? null;
} catch (error) {
if (error instanceof RemoteError) throw error;
throw new RemoteError('skillhub/installation-unavailable', '导入未完成,请检查同名技能或安装权限后重试。', { retryable: true });
}
}
@RemoteScope('agent')
async exportInstalledPackage(sourceRevision: string, itemKey: string, signal: AbortSignal): Promise<PackageExport> {
const selected = await this.readInstalledItem(sourceRevision, itemKey, signal);
try {
const target = await resolveInstalledPath({ scope: selected.item.scope, cwd: selected.agent!.session.header.cwd!, fs: selected.fs!, signal });
selected.valid(); signal.throwIfAborted();
const result = await selected.runtime!.exportPackage(selected.item, target);
selected.valid(); signal.throwIfAborted();
return { filename: result.filename, base64: Buffer.from(result.archive).toString('base64') };
} catch (error) {
signal.throwIfAborted(); selected.valid();
if (error instanceof RemoteError) throw error;
throw new RemoteError('skillhub/installation-unavailable', '无法导出:文件已变化、存在不支持的文件或超过限制。', { retryable: true });
}
}
private packageContext(sourceRevision: string) {
const id = this.ctx.invocation?.request.args.agentId;
const agent = typeof id === 'string' ? this.ctx.get('agents')?.get(SessionId(id)) : undefined;
const runtime = this.localRuntime;
const fs = agent?.ctx.get('fs');
const cwd = agent?.session.header.cwd;
const hostInstanceId = runtime?.getStatus().hostInstanceId;
if (!agent || !runtime || !fs || !cwd || !hostInstanceId || runtime.getStatus().state !== 'ready') throw installationContextError('AGENT');
const scope = { sessionId: agent.session.id, cwd, sourceRevision };
const valid = (checkSource = true) => {
if (checkSource) this.assertSource(sourceRevision);
if (this.localRuntime !== runtime || runtime.getStatus().hostInstanceId !== hostInstanceId || agent.session.header.cwd !== cwd
|| this.ctx.get('agents')?.get(SessionId(agent.session.id)) !== agent || serviceIdentity(agent.ctx.get('fs')) !== serviceIdentity(fs)) throw installationContextError('CWD');
};
valid(); return { agent, runtime, fs, scope, hostInstanceId, valid };
}
@RemoteScope('agent')
async getInstalledDetail(sourceRevision: string, itemKey: string, signal: AbortSignal): Promise<InstalledSkillDetail> {
const { item, valid } = await this.readInstalledItem(sourceRevision, itemKey, signal);
const { item, valid, runtime, agent, fs } = await this.readInstalledItem(sourceRevision, itemKey, signal);
const combined = AbortSignal.any([signal, this.lifetime.signal]);
let content: InstalledSkillDetail['content'];
try {
if (item.registry === 'local:import') {
const target = await resolveInstalledPath({ scope: item.scope, cwd: agent!.session.header.cwd!, fs: fs!, signal: combined });
const entry = await runtime!.readInstallationEntry(item, target);
valid(); combined.throwIfAborted();
if (!entry) throw new Error('local-content-unavailable');
content = { state: 'ready', detail: { detailToken: '', title: item.slug, summary: '', namespace: item.namespace, slug: item.slug,
version: item.version, versionId: 1, tabs: { versions: 'hidden', securityAudit: 'hidden', reviews: 'hidden' },
documentation: { state: 'ready', content: entry } } };
} else {
if (item.registry !== this.getContext().registryUrl.replace(/\/+$/, '')) throw new Error('other-source');
content = { state: 'ready', detail: await this.getSkillDetail(sourceRevision, item.namespace, item.slug, item.version, combined) };
}
} catch (error) {
combined.throwIfAborted();
valid();
@ -558,7 +672,7 @@ export class SkillHubService extends TypertRemoteService {
}
valid();
combined.throwIfAborted();
return { item: { itemKey, registry: item.registry, namespace: item.namespace, slug: item.slug, version: item.version, scope: item.scope, state: item.state }, content };
return { item: { itemKey, installationState: item.installationState, currentSource: item.registry === this.getContext().registryUrl.replace(/\/+$/, ''), ...(item.registry === 'local:import' ? { sourceKind: 'local-import' as const } : {}), registry: item.registry, namespace: item.namespace, slug: item.slug, version: item.version, scope: item.scope, state: item.state }, content };
}
@RemoteScope('agent')

View file

@ -210,6 +210,24 @@ export class LocalRuntime {
return receipt.promise;
}
previewPackage(...args: Parameters<NativeRuntime['previewPackage']>) { return this.call(runtime => runtime.previewPackage(...args)); }
exportPackage(...args: Parameters<NativeRuntime['exportPackage']>) { return this.call(runtime => runtime.exportPackage(...args)); }
submitPackageImport(request: NativeOperationRequest, prepare: () => Promise<PreparedNativeInstall & { archive: Uint8Array }>): Promise<NativeOperation | undefined> {
const receipt = Promise.withResolvers<NativeOperation | undefined>();
const workflow = this.call(async runtime => {
let prepared: Awaited<ReturnType<typeof prepare>> | undefined;
const accepted = await runtime.acceptInstall(request, async () => {
this.assertWritableHost(); prepared = await prepare(); return prepared.acceptance;
});
receipt.resolve(accepted);
if (!accepted || !prepared || accepted.phase !== 'accepted') return;
await this.executeAccepted(accepted, () => runtime.executePackageImport({ ...prepared!.execution,
archive: prepared!.archive, operationId: accepted.operationId, ownerId: request.ownerId }));
});
void workflow.catch(error => receipt.reject(error));
return receipt.promise;
}
private call<T>(action: (runtime: NativeRuntime) => Promise<T>): Promise<T> {
const runtime = this.runtime;
if (this.disposed || !runtime || this.status.state !== 'ready') return Promise.reject(new Error('Local installation service is unavailable'));

View file

@ -103,7 +103,7 @@ export type SkillUseSelection = { status: 'ready'; itemKey: string }
| 'multiple-usable-installations' | 'selection-timeout' };
export interface InstalledSkillList {
items: { itemKey: string; registry?: string; currentSource?: boolean; locationKey?: string; namespace: string; slug: string; version: string; scope: 'user' | 'project';
items: { itemKey: string; sourceKind?: 'local-import'; registry?: string; currentSource?: boolean; locationKey?: string; namespace: string; slug: string; version: string; scope: 'user' | 'project';
/** Optional local frontmatter for display only; never used for selection or authorization. */
displayName?: string; summary?: string;
state: 'present' | 'missing' | 'metadata-invalid' | 'mismatch' | 'unreadable'; installationState?: 'enabled' | 'disabled' }[];
@ -232,3 +232,6 @@ export interface ChangesView {
}
export interface ChangeDiffView { path: string; state: 'text' | 'binary' | 'too-large' | 'unavailable'; lines: {kind: 'context' | 'added' | 'deleted'; text: string}[]; truncated: boolean }
export interface FileResetPlanView { planId: string; expiresAt: string; hostInstanceId: string; paths: {path: string; kind: 'added' | 'modified' | 'deleted'}[] }
export interface PackageImportPreview { previewId: string; name: string; summary?: string; files: number; bytes: number; expiresAt: string }
export interface PackageExport { filename: string; base64: string }

View file

@ -26,3 +26,13 @@ test('reading view hides pending capability banners and raw frontmatter while ke
expect(html).not.toContain('href="javascript:');
expect(html).toContain('astron-sh-markdown');
});
test('local package details hide market version and modules explicitly, without interpreting version text', () => {
const client = new QueryClient();
const html = renderToStaticMarkup(<QueryClientProvider client={client}><DetailContent localPackage detail={{ ...detail, version: 'local' }} modes={{ versions: 'show', reviews: 'show', securityAudit: 'show' }} remote={remote} retry={() => {}} /></QueryClientProvider>);
expect(html).not.toContain('当前版本');
expect(html).not.toContain('role="tab" data-state="inactive"');
expect(html).toContain('正文标题');
const market = renderToStaticMarkup(<QueryClientProvider client={new QueryClient()}><DetailContent detail={{ ...detail, version: 'local' }} modes={{ versions: 'hide', reviews: 'hide', securityAudit: 'hide' }} remote={remote} retry={() => {}} /></QueryClientProvider>);
expect(market).toContain('当前版本 local');
});

View file

@ -224,7 +224,7 @@ test('disabled installation renders enable instead of use and remains an install
expect(parseManagementResult(result, 'call-1')).toEqual(result);
const html = render(result);
expect(html).toContain('已停用'); expect(html).toContain('管理安装'); expect(html).not.toContain('>启用</button>');
const advanced = render(result, undefined, true); expect(advanced).toContain('>启用</button>'); expect(advanced).not.toContain('使用此位置');
const advanced = render(result, undefined, true); expect(advanced).toContain('管理所有项目'); expect(advanced).not.toContain('>启用</button>'); expect(advanced).not.toContain('使用此位置');
expect(html).not.toContain('使用此技能'); expect(html).not.toContain('安装文件缺失');
expect(html).not.toContain('location-a'); expect(html).not.toContain('更多操作');
});
@ -325,8 +325,8 @@ test('detail installation management is inline and survives an empty refreshed i
client.setQueryData(key, { ...installed, items: [{ ...item, installationState: 'disabled' }, { ...item, itemKey: 'project-key', scope: 'project', version: '2', installationState: 'enabled' }] });
const html = renderPanel();
expect(html).toContain('aria-label="安装管理"'); expect(html).toContain('所有项目 v1.0.0'); expect(html).toContain('仅此项目 v2');
expect(html).toContain('>启用</button>'); expect(html).not.toContain('>停用</button>');
expect(html.match(/aria-label="更多操作"/g)).toHaveLength(2);
expect(html).not.toContain('>启用</button>'); expect(html).not.toContain('>停用</button>');
expect(html).toContain('aria-label="管理所有项目"'); expect(html).toContain('aria-label="管理仅此项目"'); expect(html).not.toContain('>···</button>');
expect(html).not.toContain('使用此位置'); expect(html).not.toContain('检查可用性'); expect(html).not.toContain('>卸载</button>');
expect(html).not.toContain('role="dialog"'); expect(html).not.toContain('role="combobox"'); expect(html).not.toContain('>管理安装</button>');
client.setQueryData(key, { ...installed, items: [] });

View file

@ -0,0 +1,47 @@
import { expect, test } from 'bun:test';
import { SkillHubService } from '../src/host/index.js';
import { ConfirmationPlans } from '../src/host/upgrade-plans.js';
function fixture() {
const state = { previews: 0, stale: false };
const service = Object.assign(Object.create(SkillHubService.prototype), {
lifetime: new AbortController(), packageImports: new ConfirmationPlans(), packagePreviewBytes: 0,
packageContext: () => ({ scope: { sessionId: 'session', cwd: '/project', sourceRevision: 'source' }, hostInstanceId: 'host', agent: { ctx: {} },
valid: () => { if (state.stale) throw new Error('stale context'); }, runtime: {
previewPackage: async () => { state.previews++; return { name: 'writer', summary: 'Write notes', files: 2, bytes: 120, fingerprint: 'sha256:test' }; },
} }),
});
return { service, state, signal: new AbortController().signal };
}
test('upload rejects malformed, noncanonical, empty and oversized base64 before unpacking', async () => {
const f = fixture();
for (const data of ['', 'invalid', '!!!!', 'YQ=', 'YR==', 'YQ==\n', 'A'.repeat(11_184_816)]) {
await expect(f.service.previewPackageImport('source', data, f.signal)).rejects.toThrow();
}
expect(f.state.previews).toBe(0);
});
test('package preview exposes no paths or archive and binds exact session/source context', async () => {
const f = fixture();
const preview = await f.service.previewPackageImport('source', 'YQ==', f.signal);
expect(preview).toMatchObject({ name: 'writer', files: 2, bytes: 120 });
expect(Object.keys(preview).sort()).toEqual(['bytes', 'expiresAt', 'files', 'name', 'previewId', 'summary']);
expect(f.service.packageImports.read(preview.previewId, { sessionId: 'session', cwd: '/project', sourceRevision: 'source' }).archive).toEqual(new Uint8Array([97]));
expect(() => f.service.packageImports.read(preview.previewId, { sessionId: 'other', cwd: '/project', sourceRevision: 'source' })).toThrow();
expect(() => f.service.packageImports.read(preview.previewId, { sessionId: 'session', cwd: '/project', sourceRevision: 'changed' })).toThrow();
});
test('aborted preview never retains an installation confirmation', async () => {
const f = fixture();
const aborted = AbortSignal.abort();
await expect(f.service.previewPackageImport('source', 'YQ==', aborted)).rejects.toThrow();
expect(f.service.packagePreviewBytes).toBe(0);
});
test('late preview context invalidation prevents retaining upload', async () => {
const f = fixture();
f.state.stale = true;
await expect(f.service.previewPackageImport('source', 'YQ==', f.signal)).rejects.toThrow('stale context');
expect(f.service.packagePreviewBytes).toBe(0);
});

View file

@ -0,0 +1,61 @@
import { expect, test } from 'bun:test';
import { renderToStaticMarkup } from 'react-dom/server';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { encodePackage, MAX_TRANSFER_BYTES, PackageImport, PackagePreviewContent, importProgressView, type PackageTransferServices } from '../src/client/package-transfer.js';
import { InstalledCardMetadata, installedCardVersions } from '../src/client/installed-card-metadata.js';
import type { InstalledSkillList } from '../src/host/types.js';
const item: InstalledSkillList['items'][number] = { itemKey: 'exact-install', namespace: 'local', slug: 'notes', version: 'local', scope: 'project', state: 'present', sourceKind: 'local-import', currentSource: false };
test('binary transfer encoding preserves byte values and enforces browser limit', () => {
const bytes = new Uint8Array([0, 255, 128, 10]);
expect([...atob(encodePackage(bytes))].map(char => char.charCodeAt(0))).toEqual([...bytes]);
expect(() => encodePackage(new Uint8Array())).toThrow();
expect(() => encodePackage(new Uint8Array(MAX_TRANSFER_BYTES + 1))).toThrow();
});
test('imported cards retain local provenance without suggesting registry updates or vlocal', () => {
expect(installedCardVersions([item]).label).toBe('仅此项目');
const html = renderToStaticMarkup(<InstalledCardMetadata items={[item]} />);
expect(html).toContain('仅此项目');
expect(html).not.toContain('@local');
expect(html).not.toContain('vlocal');
expect(html).not.toContain('本地导入');
});
test('initial transfer UI has one secondary import action, no automatic confirmation or host calls', () => {
let calls = 0;
const transfer: PackageTransferServices = { preview: async () => { calls++; throw new Error(); }, confirm: async () => { calls++; throw new Error(); } };
const services = { sessionId: 'session', operation: async () => { calls++; throw new Error(); } };
const html = renderToStaticMarkup(<QueryClientProvider client={new QueryClient()}><PackageImport transfer={transfer} revision="source" contextKey="session/source" services={services} onCompleted={() => {}} /></QueryClientProvider>);
expect(html).toContain('导入技能包');
expect(html).not.toContain('技能详情更多操作');
expect(html).toContain('accept=".zip,application/zip"');
expect(html).not.toContain('确认导入');
expect(calls).toBe(0);
});
test('long package preview preserves all text inside a keyboard accessible summary region', () => {
const name = 'a'.repeat(128);
const summary = 'https://example.test/' + 'x'.repeat(980);
const html = renderToStaticMarkup(<PackagePreviewContent preview={{ previewId: 'opaque', name, summary, files: 3, bytes: 1024, expiresAt: 'later' }} />);
expect(html).toContain(name);
expect(html).toContain(summary);
expect(html).toContain('aria-label="技能说明" tabindex="0"');
expect(html).toContain('astron-sh-package-summary');
expect(html).not.toContain('展开');
expect(html).toContain('3 个文件');
});
test('import progress distinguishes verification failures and real completion from confirmation', () => {
expect(importProgressView(undefined, false, false)).toEqual({ label: '等待确认导入', state: 'ready' });
expect(importProgressView(undefined, true, false)).toEqual({ label: '正在确认导入', state: 'running' });
expect(importProgressView(undefined, false, true)).toEqual({ label: '导入状态待核验', state: 'stopped' });
});
test('import result only reports success for completed observations and preserves uncertain recovery', () => {
const completed = { phase: 'completed' as const, warningCount: 0, recovery: 'not-needed' as const };
expect(importProgressView(completed, false, false)).toEqual({ label: '导入成功', state: 'complete' });
expect(importProgressView(completed, false, true).state).toBe('stopped');
expect(importProgressView({ ...completed, phase: 'failed' }, false, false)).toEqual({ label: '导入未完成', state: 'stopped' });
expect(importProgressView({ ...completed, phase: 'unknown' }, false, false).state).toBe('stopped');
expect(importProgressView({ ...completed, recovery: 'unknown' }, false, false).state).toBe('stopped');
expect(importProgressView({ ...completed, warningCount: 1 }, false, false).label).toBe('导入完成,需核验告警');
expect(importProgressView({ ...completed, phase: 'staging' }, false, false)).toEqual({ label: '正在校验技能包', state: 'running' });
});

View file

@ -55,12 +55,12 @@ describe('native M0 package', () => {
});
test('official generator publishes the declared endpoints with scoped writes and strict codec', () => {
expect(TYPERT_REMOTE.descriptors.map(item => item.method).sort()).toEqual(['acknowledgeConversationDetail', 'beginConversationManagement', 'beginInstalledUpdateScan', 'checkAvailability', 'checkInstalledUpdateScan', 'checkUpdate', 'checkVersionUpdate', 'confirmConversationManagement', 'endInstalledUpdateScan', 'executePlan', 'getCompatibility', 'getContext', 'getInstalledDetail', 'getOperation', 'getSkillDetail', 'getStatus', 'listCatalog', 'listCatalogByLabel', 'listInstallTargets', 'listInstalled', 'listLabels', 'listReviews', 'listSkills', 'listVersions', 'openConversationDetail', 'prepareSkillUse', 'prepareToggle', 'prepareUninstall', 'prepareUpgrade', 'prepareVersionUpgrade', 'recoverOperation', 'reopenConversationDetail', 'selectSkillUse', 'startInstall', 'testRegistryConnection', 'inspectLocalChanges', 'readFileChange', 'previewUpgradeChanges', 'confirmUpgradeChanges', 'prepareFileReset', 'executeFileReset'].sort());
for (const method of ['inspectLocalChanges', 'readFileChange', 'previewUpgradeChanges', 'confirmUpgradeChanges', 'prepareFileReset', 'executeFileReset', 'beginInstalledUpdateScan', 'checkInstalledUpdateScan', 'endInstalledUpdateScan', 'checkAvailability', 'beginConversationManagement', 'confirmConversationManagement', 'openConversationDetail', 'reopenConversationDetail', 'acknowledgeConversationDetail', 'listInstallTargets', 'listInstalled', 'getInstalledDetail', 'checkUpdate', 'checkVersionUpdate', 'prepareSkillUse', 'prepareToggle', 'prepareUninstall', 'prepareUpgrade', 'prepareVersionUpgrade', 'executePlan', 'startInstall', 'getOperation', 'recoverOperation']) {
expect(TYPERT_REMOTE.descriptors.map(item => item.method).sort()).toEqual(['acknowledgeConversationDetail', 'beginConversationManagement', 'beginInstalledUpdateScan', 'checkAvailability', 'checkInstalledUpdateScan', 'checkUpdate', 'checkVersionUpdate', 'confirmConversationManagement', 'endInstalledUpdateScan', 'executePlan', 'getCompatibility', 'getContext', 'getInstalledDetail', 'getOperation', 'getSkillDetail', 'getStatus', 'listCatalog', 'listCatalogByLabel', 'listInstallTargets', 'listInstalled', 'listLabels', 'listReviews', 'listSkills', 'listVersions', 'openConversationDetail', 'prepareSkillUse', 'prepareToggle', 'prepareUninstall', 'prepareUpgrade', 'prepareVersionUpgrade', 'recoverOperation', 'reopenConversationDetail', 'selectSkillUse', 'startInstall', 'testRegistryConnection', 'inspectLocalChanges', 'readFileChange', 'previewUpgradeChanges', 'confirmUpgradeChanges', 'prepareFileReset', 'executeFileReset', 'previewPackageImport', 'confirmPackageImport', 'exportInstalledPackage'].sort());
for (const method of ['inspectLocalChanges', 'readFileChange', 'previewUpgradeChanges', 'confirmUpgradeChanges', 'prepareFileReset', 'executeFileReset', 'previewPackageImport', 'confirmPackageImport', 'exportInstalledPackage', 'beginInstalledUpdateScan', 'checkInstalledUpdateScan', 'endInstalledUpdateScan', 'checkAvailability', 'beginConversationManagement', 'confirmConversationManagement', 'openConversationDetail', 'reopenConversationDetail', 'acknowledgeConversationDetail', 'listInstallTargets', 'listInstalled', 'getInstalledDetail', 'checkUpdate', 'checkVersionUpdate', 'prepareSkillUse', 'prepareToggle', 'prepareUninstall', 'prepareUpgrade', 'prepareVersionUpgrade', 'executePlan', 'startInstall', 'getOperation', 'recoverOperation']) {
const scoped = TYPERT_REMOTE.descriptors.find(item => item.method === method)!;
expect(scoped.invocation).toMatchObject({ kind: 'context', context: 'agent', wire: 'agentId' });
}
for (const method of ['inspectLocalChanges', 'readFileChange', 'previewUpgradeChanges', 'confirmUpgradeChanges', 'prepareFileReset', 'executeFileReset']) {
for (const method of ['inspectLocalChanges', 'readFileChange', 'previewUpgradeChanges', 'confirmUpgradeChanges', 'prepareFileReset', 'executeFileReset', 'previewPackageImport', 'confirmPackageImport', 'exportInstalledPackage']) {
const endpoint = TYPERT_REMOTE.descriptors.find(item => item.method === method)!;
expect(endpoint.cancellation).toEqual({ parameter: 'signal' });
expect(endpoint.result?.mode).toBe('strict');

View file

@ -4,6 +4,9 @@ import type { NativeRuntime, NativeInstallExecution, NativeRecoveryResult, Nativ
function native(): NativeRuntime {
return {
previewPackage: async () => { throw new Error('Unexpected package preview'); },
exportPackage: async () => { throw new Error('Unexpected package export'); },
executePackageImport: async () => { throw new Error('Unexpected package import'); },
inspectChanges: async () => { throw new Error('Unexpected change inspection'); },
readChangeDiff: async () => { throw new Error('Unexpected file diff'); },
prepareVersionChanges: async () => { throw new Error('Unexpected version changes'); },