import { startupDownload } from '../../bin/startup-trace.mjs'; import { accountRequiredMessage } from './desktop-mode.js'; import { AuthStore } from './auth.js'; import { createHash } from 'node:crypto'; import { ServerRegistry } from './server-registry.js'; import { HttpTransport } from './http-transport.js'; import { isWorkspaceRevisionConflict } from './hub-errors.js'; export type ResourceType = 'skill' | 'strategy' | 'persona' | 'perception'; export interface ResourceStats { downloadCount: number; starCount: number; commentCount: number; } export interface ResourceSummary { skillName?: string | null; id: string; forkedFromResourceId?: string; type: ResourceType; title: string; description: string; creator: string; creatorType: string; creatorDisplayName: string; creatorAvatarUrl: string | null; fileName: string; stats: ResourceStats; downloadUrl: string; likedByMe: boolean; createdAt: string; updatedAt: string; isInstalled: boolean; isOfficial: boolean; versionId: string; versionNumber?: string; versionDescription?: string; } export interface ResourceDetail extends ResourceSummary { artifact: { fileName: string; downloadUrl: string }; } export interface Pagination { mode: 'cursor'; nextCursor: string | null; limit: number; hasMore: boolean; } export interface ResourceListResult { items: ResourceSummary[]; total: number; pagination: Pagination; } export interface ListOptions { type?: ResourceType; q?: string; sort?: 'latest' | 'likes' | 'comments'; scope?: 'public' | 'mine'; cursor?: string; limit?: number; } export interface WorkspaceResourceSummary { skillName?: string | null; workspaceItemId: string; forkedFromResourceId?: string; resourceId: string; resourceType: ResourceType; title: string; versionId: string; equipped: boolean; hasUpdate: boolean; kind: 'owned' | 'installed'; isCreatedByMe: boolean; owner: { id: string; name: string | null; isOfficial: boolean; }; } export interface WorkspaceListResult { items: WorkspaceResourceSummary[]; nextCursor: string | null; hasMore: boolean; limit: number; } export interface WorkspaceLoadoutUpdate { skillItemIds?: readonly string[]; strategyItemIds?: readonly string[]; personaItemIds?: readonly string[]; perceptionItemIds?: readonly string[]; } const BASE = '/api/v1/hub'; /** Parse a `/` resource ref. */ export function parseResourceRef(ref: string): { type: ResourceType; id: string } { const match = ref.match(/^(skill|strategy|persona|perception)\/([^/\s]+)$/); if (!match) { throw new Error(`invalid resource ref '${ref}' (expected /)`); } return { type: match[1] as ResourceType, id: match[2] }; } interface Envelope { success?: boolean; data: T } interface RawFileEntry { relative_path: string; file_id: string; sha256: string; size_bytes: number; content_type: string; url: string; } interface RawVersion { id: string; version_number?: string; version_description?: string; title: string; description: string; icon_url?: string | null; created_at?: string | null; updated_at?: string | null; source_manifest?: { entries?: RawFileEntry[] }; } interface RawResource { skill_name?: string | null; id?: string; forked_from_resource_id?: string | null; resource_id: string; resource_type: ResourceType; owner?: { id?: string; name?: string | null; avatar_url?: string | null; is_official?: boolean }; like_count?: number; comment_count?: number; install_count?: number; is_installed?: boolean; is_official?: boolean; last_published_at?: string | null; version?: RawVersion | null; published_version?: RawVersion | null; latest_version?: RawVersion | null; } interface RawWorkspaceItem { skill_name?: string | null; workspace_item_id: string; forked_from_resource_id?: string | null; resource_id: string; resource_type: ResourceType; title?: string; version_id: string; is_equipped?: boolean; has_update?: boolean; kind?: 'owned' | 'installed'; is_created_by_me?: boolean; owner?: { id?: string; name?: string | null; is_official?: boolean }; } export interface HubSourceFileUpload { relativePath: string; filename: string; bytes: Buffer; } export interface HubUploadedSourceFile { relative_path: string; file_id: string; } export interface HubResourceMutationResult { skillName?: string | null; resourceId: string; versionId: string; workspaceItemId?: string; } function resourceVersion(resource: RawResource): RawVersion { const version = resource.latest_version ?? resource.published_version ?? resource.version; if (!version) throw new Error(`Hub resource '${resource.resource_id}' has no visible version`); return version; } function toSummary(resource: RawResource): ResourceSummary { const version = resourceVersion(resource); const firstFile = version.source_manifest?.entries?.[0]; const owner = resource.owner ?? {}; return { id: resource.resource_id ?? resource.id ?? '', forkedFromResourceId: resource.forked_from_resource_id ?? undefined, type: resource.resource_type, skillName: resource.skill_name ?? null, title: version.title, description: version.description, creator: owner.id ?? '', creatorType: owner.is_official ? 'official' : 'agent', creatorDisplayName: owner.name ?? '', creatorAvatarUrl: owner.avatar_url ?? null, fileName: firstFile?.relative_path ?? '', stats: { downloadCount: Number(resource.install_count ?? 0), starCount: Number(resource.like_count ?? 0), commentCount: Number(resource.comment_count ?? 0), }, downloadUrl: '', likedByMe: false, createdAt: version.created_at ?? '', updatedAt: version.updated_at ?? resource.last_published_at ?? '', isInstalled: resource.is_installed === true, isOfficial: resource.is_official === true || owner.is_official === true, versionId: version.id, versionNumber: version.version_number, versionDescription: version.version_description, }; } async function downloadSignedUrl(url: string): Promise { return startupDownload(async () => { const parsed = new URL(url); if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') { throw new Error(`unsupported Hub download URL protocol: ${parsed.protocol}`); } const response = await fetch(parsed, { signal: AbortSignal.timeout(30_000) }); if (!response.ok) throw new Error(`Hub download failed (${response.status})`); return Buffer.from(await response.arrayBuffer()); }); } export class HubClient { constructor( private readonly http: HttpTransport, private readonly downloadUrl: (url: string) => Promise = downloadSignedUrl, ) {} static fromAuth(opts?: { authStore?: AuthStore }): HubClient { const store = opts?.authStore ?? new AuthStore(); const profile = store.getActive(); if (!profile) throw new Error(accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.')); return HubClient.fromProfile(profile); } static fromProfile(profile: { apiKey: string; serverUrl: string }): HubClient { return new HubClient(new HttpTransport( profile.apiKey, new ServerRegistry({ lobbyUrl: profile.serverUrl }), )); } async list(opts: ListOptions = {}): Promise { const query = new URLSearchParams(); query.set('scope', opts.scope ?? 'public'); if (opts.type) query.set('resource_type', opts.type); if (opts.q) query.set('q', opts.q); if (opts.sort) query.set('sort', opts.sort); if (opts.cursor) query.set('cursor', opts.cursor); if (opts.limit !== undefined) query.set('limit', String(opts.limit)); const response = await this.http.get>(`${BASE}/resources/list?${query.toString()}`); const items = response.data.items.map(toSummary); return { items, total: items.length, pagination: { mode: 'cursor', nextCursor: response.data.next_cursor, hasMore: response.data.has_more, limit: response.data.limit, }, }; } async getResource(type: ResourceType, id: string, workspaceItemId?: string): Promise { const query = new URLSearchParams({ resource_id: id }); if (workspaceItemId) query.set('workspace_item_id', workspaceItemId); const response = await this.http.get>( `${BASE}/resources/detail?${query.toString()}`, ); if (response.data.resource_type !== type) { throw new Error(`Hub resource '${id}' is ${response.data.resource_type}, not ${type}`); } const summary = toSummary(response.data); return { ...summary, artifact: { fileName: summary.fileName, downloadUrl: '' } }; } async downloadArtifact(_type: ResourceType, id: string, workspaceItemId?: string): Promise { const query = new URLSearchParams({ resource_id: id }); if (workspaceItemId) query.set('workspace_item_id', workspaceItemId); const response = await this.http.get>( `${BASE}/resources/file-download-url?${query.toString()}`, ); return this.downloadUrl(response.data.url); } async installResource(resourceId: string): Promise<{ workspaceItemId: string; versionId: string; created: boolean }> { const response = await this.http.post>(`${BASE}/workspace/install`, { resource_id: resourceId }); return { workspaceItemId: response.data.workspace_item_id, versionId: response.data.version_id, created: response.data.created, }; } async listWorkspace(opts: { type?: ResourceType; cursor?: string; limit?: number } = {}): Promise { const query = new URLSearchParams({ filter: 'all' }); if (opts.type) query.set('resource_type', opts.type); if (opts.cursor) query.set('cursor', opts.cursor); query.set('limit', String(opts.limit ?? 100)); const response = await this.http.get>(`${BASE}/workspace/resources?${query.toString()}`); return { items: response.data.items.map((item) => ({ workspaceItemId: item.workspace_item_id, forkedFromResourceId: item.forked_from_resource_id ?? undefined, resourceId: item.resource_id, resourceType: item.resource_type, skillName: item.skill_name ?? null, title: item.title ?? '', versionId: item.version_id, equipped: item.is_equipped === true, hasUpdate: item.has_update === true, kind: item.kind === 'owned' ? 'owned' : 'installed', isCreatedByMe: item.is_created_by_me === true, owner: { id: item.owner?.id ?? '', name: item.owner?.name ?? null, isOfficial: item.owner?.is_official === true, }, })), nextCursor: response.data.next_cursor, hasMore: response.data.has_more, limit: response.data.limit, }; } async findWorkspaceItem(type: ResourceType, resourceId: string): Promise { let cursor: string | undefined; do { const page = await this.listWorkspace({ type, cursor, limit: 100 }); const found = page.items.find((item) => item.resourceId === resourceId); if (found) return found; cursor = page.hasMore && page.nextCursor ? page.nextCursor : undefined; } while (cursor); return undefined; } async syncWorkspaceItem(workspaceItemId: string): Promise<{ updated: boolean; versionId: string }> { const response = await this.http.post>( `${BASE}/workspace/sync`, { workspace_item_id: workspaceItemId }, ); return { updated: response.data.updated, versionId: response.data.version_id }; } private async updateWorkspace(path: string, body: unknown): Promise { try { return await this.http.post(path, body); } catch (error) { if (!isWorkspaceRevisionConflict(error)) throw error; // Refresh once, then retry only this explicit operation. No background // replay, extra request fields, or name-conflict replacement is allowed. await this.http.get(`${BASE}/workspace/loadout`); return this.http.post(path, body); } } async updateWorkspaceEquipment( workspaceItemId: string, equipped: boolean, ): Promise<{ workspaceItemId: string; equipped: boolean; revision: number; changed: boolean }> { const response = await this.updateWorkspace>(`${BASE}/workspace/equipment/update`, { workspace_item_id: workspaceItemId, is_equipped: equipped, }); return { workspaceItemId: response.data.workspace_item_id, equipped: response.data.is_equipped, revision: response.data.revision, changed: response.data.changed, }; } async updateWorkspaceLoadout( input: WorkspaceLoadoutUpdate, ): Promise<{ revision: number; changed: boolean }> { const body: Record = {}; if (input.skillItemIds !== undefined) body.skill_item_ids = input.skillItemIds; if (input.strategyItemIds !== undefined) body.strategy_item_ids = input.strategyItemIds; if (input.personaItemIds !== undefined) body.persona_item_ids = input.personaItemIds; if (input.perceptionItemIds !== undefined) body.perception_item_ids = input.perceptionItemIds; const response = await this.updateWorkspace>( `${BASE}/workspace/loadout/update`, body, ); return { revision: response.data.revision, changed: response.data.changed }; } async deleteWorkspaceItem(workspaceItemId: string): Promise { await this.http.post(`${BASE}/workspace/delete`, { workspace_item_id: workspaceItemId }); } async uploadFiles( fileType: string, files: readonly HubSourceFileUpload[], ): Promise { if (files.length === 0) throw new Error('Hub upload requires at least one file.'); const declarations = files.map((file) => ({ filename: file.filename, size_bytes: file.bytes.length, sha256: createHash('sha256').update(file.bytes).digest('hex'), })); const prepared = await this.http.post; content_type: string; }>; }>>('/api/v1/files/prepare', { file_type: fileType, files: declarations }); if (prepared.data.items.length !== files.length) throw new Error('Hub upload preparation count mismatch.'); for (let index = 0; index < files.length; index += 1) { const file = files[index]!; const policy = prepared.data.items[index]!; const form = new FormData(); for (const [name, value] of Object.entries(policy.form_fields)) form.append(name, value); form.append( policy.file_field, new Blob([Uint8Array.from(file.bytes)], { type: policy.content_type }), file.filename, ); const response = await fetch(policy.upload_url, { method: 'POST', body: form, signal: AbortSignal.timeout(30_000), }); if (!response.ok) throw new Error(`Hub object upload failed (${response.status}).`); } const fileIds = prepared.data.items.map((item) => item.file_id); const completed = await this.http.post; }>>('/api/v1/files/complete', { file_ids: fileIds }); if ( completed.data.items.length !== fileIds.length || completed.data.items.some((item) => item.status !== 'ready') ) throw new Error('Hub upload completion failed.'); return files.map((file, index) => ({ relative_path: file.relativePath, file_id: fileIds[index]!, })); } async createPrivateResource(input: { resourceType: ResourceType; title: string; description: string; sourceFiles: readonly HubUploadedSourceFile[]; packageFileId?: string; forkFromWorkspaceItemId?: string; strategyKind?: 'long' | 'short'; }): Promise { const response = await this.http.post>(`${BASE}/resources/create`, { resource_type: input.resourceType, version_number: '1.0.0', version_description: '本地修改同步', ...(input.resourceType === 'strategy' ? { strategy_kind: input.strategyKind ?? 'long' } : {}), title: input.title, description: input.description, icon_url: null, source_files: input.sourceFiles, package_file_id: input.packageFileId ?? null, fork_from_workspace_item_id: input.forkFromWorkspaceItemId ?? null, }); return { resourceId: response.data.resource_id, versionId: response.data.latest_version.id, skillName: response.data.skill_name ?? null, ...(response.data.workspace_item_id ? { workspaceItemId: response.data.workspace_item_id } : {}), }; } async createPrivateVersion(input: { resourceId: string; baseVersionId: string; title: string; description: string; sourceFiles: readonly HubUploadedSourceFile[]; packageFileId?: string; versionNumber: string; strategyKind?: 'long' | 'short'; }): Promise { const response = await this.http.post>(`${BASE}/resources/version/create`, { resource_id: input.resourceId, base_version_id: input.baseVersionId, version_number: input.versionNumber, version_description: '本地修改同步', ...(input.strategyKind ? { strategy_kind: input.strategyKind } : {}), title: input.title, description: input.description, icon_url: null, source_files: input.sourceFiles, package_file_id: input.packageFileId ?? null, }); return { resourceId: response.data.resource_id, versionId: response.data.latest_version.id, skillName: response.data.skill_name ?? null, }; } }