@myclaw163/clawclaw-cli 0.8.12 → 0.8.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,94 @@
1
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import type { AuthProfile } from './auth.js';
4
+ import {
5
+ classifyStrategyLifecycle,
6
+ registerDiscoveredCapability,
7
+ type CapabilityWorkspaceEntry,
8
+ } from './capability-workspace.js';
9
+ import { listPersonaPresets } from './persona.js';
10
+ import { readSkillName } from './skill-host.js';
11
+ import {
12
+ ensureAccountUserDataLayout,
13
+ getUserDataAccountBehaviorsDir,
14
+ getUserDataAccountPerceptionsDir,
15
+ getUserDataAccountPersonasDir,
16
+ getUserDataAccountSkillsDir,
17
+ } from './user-data.js';
18
+ import {
19
+ listClawclawBehaviorSources,
20
+ type ResolvedClawclawBehaviorSource,
21
+ } from '../runtime/clawclaw/plugins/behavior/behavior-source.js';
22
+ import {
23
+ listClawclawPerceptionSourcesInDirectory,
24
+ type ResolvedClawclawPerceptionSource,
25
+ } from '../runtime/clawclaw/plugins/perception/perception-source.js';
26
+
27
+ export interface DiscoveredLocalCapabilities {
28
+ behaviors: Array<{ source: ResolvedClawclawBehaviorSource; entry: CapabilityWorkspaceEntry }>;
29
+ perceptions: Array<{ source: ResolvedClawclawPerceptionSource; entry: CapabilityWorkspaceEntry }>;
30
+ personas: CapabilityWorkspaceEntry[];
31
+ skills: CapabilityWorkspaceEntry[];
32
+ }
33
+
34
+ export function discoverLocalCapabilities(
35
+ workspaceDir: string,
36
+ profile: Pick<AuthProfile, 'apiKey'>,
37
+ ): DiscoveredLocalCapabilities {
38
+ ensureAccountUserDataLayout(workspaceDir, profile);
39
+ const behaviors = listClawclawBehaviorSources(
40
+ getUserDataAccountBehaviorsDir(workspaceDir, profile),
41
+ ).map((source) => ({
42
+ source,
43
+ entry: registerDiscoveredCapability(workspaceDir, profile, {
44
+ type: 'behavior',
45
+ path: source.sourcePath,
46
+ runtimeId: source.id,
47
+ title: source.name,
48
+ description: source.description,
49
+ strategyLifecycle: classifyStrategyLifecycle(readFileSync(source.sourcePath, 'utf8')),
50
+ }),
51
+ }));
52
+ const perceptions = listClawclawPerceptionSourcesInDirectory(
53
+ getUserDataAccountPerceptionsDir(workspaceDir, profile),
54
+ ).map((source) => ({
55
+ source,
56
+ entry: registerDiscoveredCapability(workspaceDir, profile, {
57
+ type: 'perception',
58
+ path: source.sourcePath,
59
+ runtimeId: source.id,
60
+ title: source.name,
61
+ description: source.description,
62
+ }),
63
+ }));
64
+ const personas = listPersonaPresets(
65
+ getUserDataAccountPersonasDir(workspaceDir, profile),
66
+ ).map((preset) => registerDiscoveredCapability(workspaceDir, profile, {
67
+ type: 'persona',
68
+ path: preset.path,
69
+ runtimeId: preset.id,
70
+ title: preset.name,
71
+ description: `Persona ${preset.name}`,
72
+ }));
73
+ const skillsRoot = getUserDataAccountSkillsDir(workspaceDir, profile);
74
+ const skills = existsSync(skillsRoot)
75
+ ? readdirSync(skillsRoot, { withFileTypes: true }).flatMap((item) => {
76
+ if (!item.isDirectory()) return [];
77
+ const path = join(skillsRoot, item.name);
78
+ try {
79
+ if (!statSync(path).isDirectory()) return [];
80
+ } catch {
81
+ return [];
82
+ }
83
+ const name = readSkillName(path);
84
+ return name ? [registerDiscoveredCapability(workspaceDir, profile, {
85
+ type: 'skill',
86
+ path,
87
+ runtimeId: name,
88
+ title: name,
89
+ description: `Skill ${name}`,
90
+ })] : [];
91
+ })
92
+ : [];
93
+ return { behaviors, perceptions, personas, skills };
94
+ }
@@ -0,0 +1,291 @@
1
+ import {
2
+ cpSync,
3
+ existsSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ renameSync,
7
+ writeFileSync,
8
+ } from 'node:fs';
9
+ import { randomUUID } from 'node:crypto';
10
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
11
+ import type { AuthProfile } from './auth.js';
12
+ import {
13
+ getUserDataAccountCapabilitiesDir,
14
+ getUserDataAccountCapabilityRegistryFile,
15
+ getUserDataAccountDraftsDir,
16
+ getUserDataAccountDir,
17
+ } from './user-data.js';
18
+
19
+ export type CapabilityWorkspaceType = 'behavior' | 'perception' | 'persona' | 'skill';
20
+ export type CapabilitySelection = 'pending' | 'equipped' | 'unequipped';
21
+ export type StrategyLifecycle = 'long' | 'short';
22
+
23
+ export interface CapabilityHubIdentity {
24
+ resourceId: string;
25
+ versionId: string;
26
+ workspaceItemId?: string;
27
+ publisher: 'official' | 'self' | 'community';
28
+ baseSha256?: string;
29
+ lastUploadedSha256?: string;
30
+ pendingBackpackRestoreResourceId?: string;
31
+ observedCloudVersionId?: string;
32
+ }
33
+
34
+ export interface CapabilityWorkspaceEntry {
35
+ key: string;
36
+ type: CapabilityWorkspaceType;
37
+ origin: 'local' | 'hub';
38
+ relativePath: string;
39
+ runtimeId: string;
40
+ title: string;
41
+ description: string;
42
+ selection: CapabilitySelection;
43
+ strategyLifecycle?: StrategyLifecycle;
44
+ conflictChoice?: 'local';
45
+ hub?: CapabilityHubIdentity;
46
+ discoveredAt: string;
47
+ updatedAt: string;
48
+ }
49
+
50
+ export interface CapabilityWorkspaceRegistry {
51
+ format: 1;
52
+ entries: Record<string, CapabilityWorkspaceEntry>;
53
+ }
54
+
55
+ const EMPTY = (): CapabilityWorkspaceRegistry => ({ format: 1, entries: {} });
56
+ const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/;
57
+
58
+ function pathInside(root: string, candidate: string): boolean {
59
+ const child = relative(resolve(root), resolve(candidate));
60
+ return child === '' || (!child.startsWith('..') && !isAbsolute(child));
61
+ }
62
+
63
+ function normalizedRelativePath(root: string, path: string): string {
64
+ const absolute = resolve(path);
65
+ if (!pathInside(root, absolute)) throw new Error('capability_workspace_path_escape');
66
+ const value = relative(resolve(root), absolute).replaceAll('\\', '/');
67
+ if (!value || value.split('/').some((segment) => !segment || segment === '.' || segment === '..')) {
68
+ throw new Error('capability_workspace_relative_path_invalid');
69
+ }
70
+ return value;
71
+ }
72
+
73
+ function registryKey(type: CapabilityWorkspaceType, relativePath: string): string {
74
+ return `${type}:${relativePath}`;
75
+ }
76
+
77
+ function writeRegistryFile(path: string, registry: CapabilityWorkspaceRegistry): void {
78
+ mkdirSync(dirname(path), { recursive: true });
79
+ const temporary = `${path}.${randomUUID()}.tmp`;
80
+ writeFileSync(temporary, `${JSON.stringify(registry, null, 2)}\n`, 'utf8');
81
+ renameSync(temporary, path);
82
+ }
83
+
84
+ export function readCapabilityWorkspaceRegistry(
85
+ workspaceDir: string,
86
+ profile: Pick<AuthProfile, 'apiKey'>,
87
+ ): CapabilityWorkspaceRegistry {
88
+ const path = getUserDataAccountCapabilityRegistryFile(workspaceDir, profile);
89
+ if (!existsSync(path)) return EMPTY();
90
+ try {
91
+ const value = JSON.parse(readFileSync(path, 'utf8')) as CapabilityWorkspaceRegistry;
92
+ if (value.format !== 1 || !value.entries || typeof value.entries !== 'object') return EMPTY();
93
+ return value;
94
+ } catch {
95
+ return EMPTY();
96
+ }
97
+ }
98
+
99
+ export function writeCapabilityWorkspaceRegistry(
100
+ workspaceDir: string,
101
+ profile: Pick<AuthProfile, 'apiKey'>,
102
+ registry: CapabilityWorkspaceRegistry,
103
+ ): void {
104
+ writeRegistryFile(getUserDataAccountCapabilityRegistryFile(workspaceDir, profile), registry);
105
+ }
106
+
107
+ export function registerDiscoveredCapability(
108
+ workspaceDir: string,
109
+ profile: Pick<AuthProfile, 'apiKey'>,
110
+ input: {
111
+ type: CapabilityWorkspaceType;
112
+ path: string;
113
+ runtimeId: string;
114
+ title?: string;
115
+ description?: string;
116
+ strategyLifecycle?: StrategyLifecycle;
117
+ hub?: CapabilityHubIdentity;
118
+ selectedByHub?: boolean;
119
+ },
120
+ ): CapabilityWorkspaceEntry {
121
+ const validRuntimeId = input.type === 'persona'
122
+ ? !!input.runtimeId.trim()
123
+ && input.runtimeId.length <= 255
124
+ && !/[\\/\u0000-\u001f]/u.test(input.runtimeId)
125
+ : SAFE_ID.test(input.runtimeId);
126
+ if (!validRuntimeId) throw new Error('capability_workspace_runtime_id_invalid');
127
+ const root = getUserDataAccountCapabilitiesDir(workspaceDir, profile);
128
+ const relativePath = normalizedRelativePath(root, input.path);
129
+ const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
130
+ const existingByResource = input.hub
131
+ ? Object.values(registry.entries).find((entry) => (
132
+ entry.type === input.type && entry.hub?.resourceId === input.hub?.resourceId
133
+ ))
134
+ : undefined;
135
+ const key = existingByResource?.key ?? registryKey(input.type, relativePath);
136
+ const now = new Date().toISOString();
137
+ const previous = registry.entries[key];
138
+ const entry: CapabilityWorkspaceEntry = {
139
+ key,
140
+ type: input.type,
141
+ origin: previous?.origin ?? (input.selectedByHub ? 'hub' : 'local'),
142
+ relativePath,
143
+ runtimeId: input.runtimeId,
144
+ title: input.title?.trim() || previous?.title || input.runtimeId,
145
+ description: input.description?.trim() || previous?.description || `${input.type} ${input.runtimeId}`,
146
+ selection: input.selectedByHub
147
+ ? 'equipped'
148
+ : previous?.selection ?? 'pending',
149
+ ...(input.strategyLifecycle ? { strategyLifecycle: input.strategyLifecycle } : {}),
150
+ ...(previous?.conflictChoice ? { conflictChoice: previous.conflictChoice } : {}),
151
+ ...(input.hub ? { hub: { ...previous?.hub, ...input.hub } } : previous?.hub ? { hub: previous.hub } : {}),
152
+ discoveredAt: previous?.discoveredAt ?? now,
153
+ updatedAt: now,
154
+ };
155
+ if (previous && previous.relativePath !== relativePath) delete registry.entries[previous.key];
156
+ registry.entries[key] = entry;
157
+ writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
158
+ return entry;
159
+ }
160
+
161
+ export function capabilityEntryForPath(
162
+ workspaceDir: string,
163
+ profile: Pick<AuthProfile, 'apiKey'>,
164
+ type: CapabilityWorkspaceType,
165
+ path: string,
166
+ ): CapabilityWorkspaceEntry | undefined {
167
+ const root = getUserDataAccountCapabilitiesDir(workspaceDir, profile);
168
+ const relativePath = normalizedRelativePath(root, path);
169
+ const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
170
+ return registry.entries[registryKey(type, relativePath)]
171
+ ?? Object.values(registry.entries).find((entry) => (
172
+ entry.type === type && entry.relativePath === relativePath
173
+ ));
174
+ }
175
+
176
+ export function capabilityEntryForHubResource(
177
+ workspaceDir: string,
178
+ profile: Pick<AuthProfile, 'apiKey'>,
179
+ type: CapabilityWorkspaceType,
180
+ resourceId: string,
181
+ ): CapabilityWorkspaceEntry | undefined {
182
+ return Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
183
+ .find((entry) => entry.type === type && entry.hub?.resourceId === resourceId);
184
+ }
185
+
186
+ export function setCapabilitySelection(
187
+ workspaceDir: string,
188
+ profile: Pick<AuthProfile, 'apiKey'>,
189
+ type: CapabilityWorkspaceType,
190
+ runtimeId: string,
191
+ equipped: boolean,
192
+ ): CapabilityWorkspaceEntry {
193
+ const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
194
+ const matches = Object.values(registry.entries)
195
+ .filter((entry) => entry.type === type && entry.runtimeId === runtimeId && entry.origin === 'local');
196
+ if (matches.length !== 1) throw new Error(`capability_selection_${matches.length === 0 ? 'not_found' : 'ambiguous'}:${type}:${runtimeId}`);
197
+ const entry = matches[0]!;
198
+ entry.selection = equipped ? 'equipped' : 'unequipped';
199
+ entry.updatedAt = new Date().toISOString();
200
+ writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
201
+ return entry;
202
+ }
203
+
204
+ export function updateCapabilityHubIdentity(
205
+ workspaceDir: string,
206
+ profile: Pick<AuthProfile, 'apiKey'>,
207
+ key: string,
208
+ hub: CapabilityHubIdentity,
209
+ ): CapabilityWorkspaceEntry {
210
+ const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
211
+ const entry = registry.entries[key];
212
+ if (!entry) throw new Error(`capability_workspace_entry_missing:${key}`);
213
+ entry.hub = { ...entry.hub, ...hub };
214
+ entry.updatedAt = new Date().toISOString();
215
+ writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
216
+ return entry;
217
+ }
218
+
219
+ export function setCapabilityConflictChoice(
220
+ workspaceDir: string,
221
+ profile: Pick<AuthProfile, 'apiKey'>,
222
+ key: string,
223
+ choice: 'local' | undefined,
224
+ ): CapabilityWorkspaceEntry {
225
+ const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
226
+ const entry = registry.entries[key];
227
+ if (!entry) throw new Error(`capability_workspace_entry_missing:${key}`);
228
+ if (choice) entry.conflictChoice = choice;
229
+ else delete entry.conflictChoice;
230
+ entry.updatedAt = new Date().toISOString();
231
+ writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
232
+ return entry;
233
+ }
234
+
235
+ export function pendingCapabilitySelections(
236
+ workspaceDir: string,
237
+ profile: Pick<AuthProfile, 'apiKey'>,
238
+ ): readonly CapabilityWorkspaceEntry[] {
239
+ return Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
240
+ .filter((entry) => entry.origin === 'local' && entry.selection === 'pending')
241
+ .sort((left, right) => left.discoveredAt.localeCompare(right.discoveredAt));
242
+ }
243
+
244
+ export function capabilityWorkspacePath(
245
+ workspaceDir: string,
246
+ profile: Pick<AuthProfile, 'apiKey'>,
247
+ entry: Pick<CapabilityWorkspaceEntry, 'relativePath'>,
248
+ ): string {
249
+ const root = getUserDataAccountCapabilitiesDir(workspaceDir, profile);
250
+ const path = resolve(root, ...entry.relativePath.split('/'));
251
+ if (!pathInside(root, path)) throw new Error('capability_workspace_path_escape');
252
+ return path;
253
+ }
254
+
255
+ export function saveCapabilityDraft(
256
+ workspaceDir: string,
257
+ profile: Pick<AuthProfile, 'apiKey'>,
258
+ input: { type: CapabilityWorkspaceType; runtimeId: string; bytes: Buffer; extension: string },
259
+ ): string {
260
+ const safeRuntimeId = SAFE_ID.test(input.runtimeId) ? input.runtimeId : 'capability';
261
+ const directory = join(
262
+ getUserDataAccountDraftsDir(workspaceDir, profile),
263
+ input.type,
264
+ `${safeRuntimeId}-${randomUUID()}`,
265
+ );
266
+ mkdirSync(directory, { recursive: true });
267
+ const path = join(directory, `${safeRuntimeId}${input.extension}`);
268
+ writeFileSync(path, input.bytes);
269
+ return path;
270
+ }
271
+
272
+ export function saveCapabilityDirectoryDraft(
273
+ workspaceDir: string,
274
+ profile: Pick<AuthProfile, 'apiKey'>,
275
+ input: { type: CapabilityWorkspaceType; runtimeId: string; sourcePath: string },
276
+ ): string {
277
+ const safeRuntimeId = SAFE_ID.test(input.runtimeId) ? input.runtimeId : 'capability';
278
+ const directory = join(
279
+ getUserDataAccountDraftsDir(workspaceDir, profile),
280
+ input.type,
281
+ `${safeRuntimeId}-${randomUUID()}`,
282
+ );
283
+ mkdirSync(dirname(directory), { recursive: true });
284
+ cpSync(input.sourcePath, directory, { recursive: true, errorOnExist: true });
285
+ return directory;
286
+ }
287
+
288
+ /** Product classification: a Behavior that can emit a finish effect is short. */
289
+ export function classifyStrategyLifecycle(source: string): StrategyLifecycle {
290
+ return /\bfinish\s*:|\bfinished\s*\(/.test(source) ? 'short' : 'long';
291
+ }
@@ -1,4 +1,5 @@
1
1
  import { AuthStore } from './auth.js';
2
+ import { createHash } from 'node:crypto';
2
3
  import { ServerRegistry } from './server-registry.js';
3
4
  import { HttpTransport } from './http-transport.js';
4
5
 
@@ -131,6 +132,23 @@ interface RawWorkspaceItem {
131
132
  has_update?: boolean;
132
133
  }
133
134
 
135
+ export interface HubSourceFileUpload {
136
+ relativePath: string;
137
+ filename: string;
138
+ bytes: Buffer;
139
+ }
140
+
141
+ export interface HubUploadedSourceFile {
142
+ relative_path: string;
143
+ file_id: string;
144
+ }
145
+
146
+ export interface HubResourceMutationResult {
147
+ resourceId: string;
148
+ versionId: string;
149
+ workspaceItemId?: string;
150
+ }
151
+
134
152
  function resourceVersion(resource: RawResource): RawVersion {
135
153
  const version = resource.latest_version ?? resource.published_version ?? resource.version;
136
154
  if (!version) throw new Error(`Hub resource '${resource.resource_id}' has no visible version`);
@@ -223,9 +241,11 @@ export class HubClient {
223
241
  };
224
242
  }
225
243
 
226
- async getResource(type: ResourceType, id: string): Promise<ResourceDetail> {
244
+ async getResource(type: ResourceType, id: string, workspaceItemId?: string): Promise<ResourceDetail> {
245
+ const query = new URLSearchParams({ resource_id: id });
246
+ if (workspaceItemId) query.set('workspace_item_id', workspaceItemId);
227
247
  const response = await this.http.get<Envelope<RawResource>>(
228
- `${BASE}/resources/detail?resource_id=${encodeURIComponent(id)}`,
248
+ `${BASE}/resources/detail?${query.toString()}`,
229
249
  );
230
250
  if (response.data.resource_type !== type) {
231
251
  throw new Error(`Hub resource '${id}' is ${response.data.resource_type}, not ${type}`);
@@ -234,9 +254,11 @@ export class HubClient {
234
254
  return { ...summary, artifact: { fileName: summary.fileName, downloadUrl: '' } };
235
255
  }
236
256
 
237
- async downloadArtifact(_type: ResourceType, id: string): Promise<Buffer> {
257
+ async downloadArtifact(_type: ResourceType, id: string, workspaceItemId?: string): Promise<Buffer> {
258
+ const query = new URLSearchParams({ resource_id: id });
259
+ if (workspaceItemId) query.set('workspace_item_id', workspaceItemId);
238
260
  const response = await this.http.get<Envelope<{ url: string }>>(
239
- `${BASE}/resources/file-download-url?resource_id=${encodeURIComponent(id)}`,
261
+ `${BASE}/resources/file-download-url?${query.toString()}`,
240
262
  );
241
263
  return this.downloadUrl(response.data.url);
242
264
  }
@@ -303,4 +325,109 @@ export class HubClient {
303
325
  async deleteWorkspaceItem(workspaceItemId: string): Promise<void> {
304
326
  await this.http.post(`${BASE}/workspace/delete`, { workspace_item_id: workspaceItemId });
305
327
  }
328
+
329
+ async uploadFiles(
330
+ fileType: string,
331
+ files: readonly HubSourceFileUpload[],
332
+ ): Promise<readonly HubUploadedSourceFile[]> {
333
+ if (files.length === 0) throw new Error('Hub upload requires at least one file.');
334
+ const declarations = files.map((file) => ({
335
+ filename: file.filename,
336
+ size_bytes: file.bytes.length,
337
+ sha256: createHash('sha256').update(file.bytes).digest('hex'),
338
+ }));
339
+ const prepared = await this.http.post<Envelope<{
340
+ items: Array<{
341
+ file_id: string;
342
+ upload_url: string;
343
+ file_field: string;
344
+ form_fields: Record<string, string>;
345
+ content_type: string;
346
+ }>;
347
+ }>>('/api/v1/files/prepare', { file_type: fileType, files: declarations });
348
+ if (prepared.data.items.length !== files.length) throw new Error('Hub upload preparation count mismatch.');
349
+ for (let index = 0; index < files.length; index += 1) {
350
+ const file = files[index]!;
351
+ const policy = prepared.data.items[index]!;
352
+ const form = new FormData();
353
+ for (const [name, value] of Object.entries(policy.form_fields)) form.append(name, value);
354
+ form.append(
355
+ policy.file_field,
356
+ new Blob([Uint8Array.from(file.bytes)], { type: policy.content_type }),
357
+ file.filename,
358
+ );
359
+ const response = await fetch(policy.upload_url, {
360
+ method: 'POST',
361
+ body: form,
362
+ signal: AbortSignal.timeout(30_000),
363
+ });
364
+ if (!response.ok) throw new Error(`Hub object upload failed (${response.status}).`);
365
+ }
366
+ const fileIds = prepared.data.items.map((item) => item.file_id);
367
+ const completed = await this.http.post<Envelope<{
368
+ items: Array<{ file_id: string; status: string }>;
369
+ }>>('/api/v1/files/complete', { file_ids: fileIds });
370
+ if (
371
+ completed.data.items.length !== fileIds.length
372
+ || completed.data.items.some((item) => item.status !== 'ready')
373
+ ) throw new Error('Hub upload completion failed.');
374
+ return files.map((file, index) => ({
375
+ relative_path: file.relativePath,
376
+ file_id: fileIds[index]!,
377
+ }));
378
+ }
379
+
380
+ async createPrivateResource(input: {
381
+ resourceType: ResourceType;
382
+ title: string;
383
+ description: string;
384
+ sourceFiles: readonly HubUploadedSourceFile[];
385
+ packageFileId?: string;
386
+ forkFromWorkspaceItemId?: string;
387
+ }): Promise<HubResourceMutationResult> {
388
+ const response = await this.http.post<Envelope<{
389
+ resource_id: string;
390
+ latest_version: { id: string };
391
+ workspace_item_id?: string;
392
+ }>>(`${BASE}/resources/create`, {
393
+ resource_type: input.resourceType,
394
+ title: input.title,
395
+ description: input.description,
396
+ icon_url: null,
397
+ source_files: input.sourceFiles,
398
+ package_file_id: input.packageFileId ?? null,
399
+ fork_from_workspace_item_id: input.forkFromWorkspaceItemId ?? null,
400
+ });
401
+ return {
402
+ resourceId: response.data.resource_id,
403
+ versionId: response.data.latest_version.id,
404
+ ...(response.data.workspace_item_id ? { workspaceItemId: response.data.workspace_item_id } : {}),
405
+ };
406
+ }
407
+
408
+ async createPrivateVersion(input: {
409
+ resourceId: string;
410
+ baseVersionId: string;
411
+ title: string;
412
+ description: string;
413
+ sourceFiles: readonly HubUploadedSourceFile[];
414
+ packageFileId?: string;
415
+ }): Promise<HubResourceMutationResult> {
416
+ const response = await this.http.post<Envelope<{
417
+ resource_id: string;
418
+ latest_version: { id: string };
419
+ }>>(`${BASE}/resources/version/create`, {
420
+ resource_id: input.resourceId,
421
+ base_version_id: input.baseVersionId,
422
+ title: input.title,
423
+ description: input.description,
424
+ icon_url: null,
425
+ source_files: input.sourceFiles,
426
+ package_file_id: input.packageFileId ?? null,
427
+ });
428
+ return {
429
+ resourceId: response.data.resource_id,
430
+ versionId: response.data.latest_version.id,
431
+ };
432
+ }
306
433
  }
@@ -8,7 +8,6 @@ import {
8
8
  getUserDataAccountPersonaSelectionFile,
9
9
  getUserDataAccountHubPersonasDir,
10
10
  getUserDataAccountPersonasDir,
11
- getUserDataPersonaFile,
12
11
  } from './user-data.js';
13
12
  import {
14
13
  readLocalAgentWorkspaceSnapshot,
@@ -144,28 +143,6 @@ function hubPersona(
144
143
  return { path: working ?? null, source: 'hub', resourceId: item.resourceId };
145
144
  }
146
145
 
147
- function migrateLegacyPersonaWithoutHub(
148
- workspaceDir: string,
149
- profile: Pick<AuthProfile, 'apiKey'>,
150
- ): PersonaSelection | undefined {
151
- const legacy = getUserDataPersonaFile(workspaceDir, profile);
152
- if (!existsSync(legacy)) return undefined;
153
- const content = readFileSync(legacy, 'utf8');
154
- if (!content.trim()) return undefined;
155
- const directory = getUserDataAccountPersonasDir(workspaceDir, profile);
156
- mkdirSync(directory, { recursive: true });
157
- let id = 'legacy';
158
- let target = join(directory, `${id}.md`);
159
- if (existsSync(target) && readFileSync(target, 'utf8') !== content) {
160
- id = `legacy-${randomUUID().slice(0, 8)}`;
161
- target = join(directory, `${id}.md`);
162
- }
163
- if (!existsSync(target)) writeFileSync(target, content, 'utf8');
164
- const selection = { source: 'local', id } as const;
165
- writePersonaSelection(workspaceDir, profile, selection);
166
- return selection;
167
- }
168
-
169
146
  export function resolveActivePersonaFile(authStore = new AuthStore()): ResolvedPersonaFile {
170
147
  const profile = authStore.getActive();
171
148
  if (!profile) throw new Error('Not logged in.');
@@ -174,7 +151,7 @@ export function resolveActivePersonaFile(authStore = new AuthStore()): ResolvedP
174
151
  const snapshot = readLocalAgentWorkspaceSnapshot(workspaceDir, profile);
175
152
  const selectedHub = hubPersona(workspaceDir, profile, snapshot);
176
153
  const selection = readPersonaSelection(workspaceDir, profile)
177
- ?? (selectedHub ? { source: 'hub' as const } : migrateLegacyPersonaWithoutHub(workspaceDir, profile));
154
+ ?? (selectedHub ? { source: 'hub' as const } : { source: 'none' as const });
178
155
  if (selection?.source === 'local') {
179
156
  const preset = findPersonaPreset(selection.id, getUserDataAccountPersonasDir(workspaceDir, profile));
180
157
  return { path: preset?.path ?? null, source: 'local', id: selection.id };
@@ -2,17 +2,22 @@ import { spawnSync } from 'node:child_process';
2
2
  import {
3
3
  cpSync,
4
4
  existsSync,
5
+ lstatSync,
5
6
  mkdirSync,
6
7
  readFileSync,
8
+ realpathSync,
7
9
  readdirSync,
8
10
  renameSync,
9
11
  rmSync,
10
12
  statSync,
13
+ symlinkSync,
14
+ unlinkSync,
11
15
  } from 'node:fs';
12
16
  import { createHash, randomUUID } from 'node:crypto';
13
17
  import { homedir } from 'node:os';
14
18
  import { dirname, join, resolve } from 'node:path';
15
19
  import { createRequire } from 'node:module';
20
+ import { fileURLToPath } from 'node:url';
16
21
 
17
22
  const require = createRequire(import.meta.url);
18
23
 
@@ -106,6 +111,13 @@ export function agentSkillTargets(name: string): string[] {
106
111
  ];
107
112
  }
108
113
 
114
+ export function resolveBundledClawclawSkill(): string {
115
+ const dev = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'skills', 'clawclaw');
116
+ if (existsSync(join(dev, 'SKILL.md'))) return dev;
117
+ const packageRoot = dirname(require.resolve('@myclaw163/clawclaw-cli/package.json'));
118
+ return join(packageRoot, 'skills', 'clawclaw');
119
+ }
120
+
109
121
  export function hashAgentSkillDirectory(path: string): string | undefined {
110
122
  if (!existsSync(path) || !statSync(path).isDirectory()) return undefined;
111
123
  const root = resolve(path);
@@ -155,6 +167,57 @@ export function overwriteAgentSkillTarget(sourcePath: string, targetPath: string
155
167
  }
156
168
  }
157
169
 
170
+ /** Point one host at the account's canonical Skill without consuming legacy real directories. */
171
+ export function linkAgentSkillTarget(sourcePath: string, targetPath: string): SkillHostMutationResult {
172
+ const source = resolve(findSkillRoot(sourcePath));
173
+ const target = resolve(targetPath);
174
+ const stage = `${target}.ccl-link-${randomUUID()}`;
175
+ const displaced = `${target}.ccl-old-link-${randomUUID()}`;
176
+ let moved = false;
177
+ try {
178
+ if (!existsSync(join(source, 'SKILL.md'))) return { ok: false, error: 'canonical skill is invalid' };
179
+ mkdirSync(dirname(target), { recursive: true });
180
+ if (existsSync(target)) {
181
+ if (!lstatSync(target).isSymbolicLink()) {
182
+ return { ok: false, error: 'legacy real skill directory is unsupported and was preserved' };
183
+ }
184
+ try {
185
+ if (resolve(realpathSync(target)) === source) {
186
+ return { ok: true };
187
+ }
188
+ } catch {}
189
+ }
190
+ symlinkSync(source, stage, process.platform === 'win32' ? 'junction' : 'dir');
191
+ if (existsSync(target)) {
192
+ renameSync(target, displaced);
193
+ moved = true;
194
+ }
195
+ renameSync(stage, target);
196
+ if (moved) unlinkSync(displaced);
197
+ return { ok: true };
198
+ } catch (error) {
199
+ if (existsSync(stage)) unlinkSync(stage);
200
+ if (moved && !existsSync(target) && existsSync(displaced)) {
201
+ try { renameSync(displaced, target); } catch {}
202
+ }
203
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
204
+ }
205
+ }
206
+
207
+ export function unlinkAgentSkillTarget(targetPath: string): SkillHostMutationResult {
208
+ const target = resolve(targetPath);
209
+ try {
210
+ if (!existsSync(target)) return { ok: true };
211
+ if (!lstatSync(target).isSymbolicLink()) {
212
+ return { ok: false, error: 'legacy real skill directory is unsupported and was preserved' };
213
+ }
214
+ unlinkSync(target);
215
+ return { ok: true };
216
+ } catch (error) {
217
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
218
+ }
219
+ }
220
+
158
221
  export function unregisterAgentSkill(name: string): SkillHostMutationResult {
159
222
  return runSkillsCli(['remove', name, '-g', '-y']);
160
223
  }