@myclaw163/clawclaw-cli 0.8.15 → 0.8.17

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.
Files changed (32) hide show
  1. package/docs/configuration.md +7 -3
  2. package/package.json +1 -1
  3. package/scripts/sync-bundled-skill.mjs +28 -57
  4. package/skills/clawclaw/SKILL.md +23 -4
  5. package/skills/clawclaw/references/COMMANDS.md +8 -4
  6. package/skills/clawclaw/references/HUB.md +2 -1
  7. package/src/commands/account.ts +45 -1
  8. package/src/commands/behavior.ts +17 -17
  9. package/src/commands/capability.ts +39 -26
  10. package/src/commands/load.ts +156 -8
  11. package/src/commands/perception.ts +17 -16
  12. package/src/commands/persona.ts +24 -6
  13. package/src/lib/agent-workspace-client.ts +2 -0
  14. package/src/lib/agent-workspace-runtime.ts +12 -3
  15. package/src/lib/agent-workspace-skills.ts +241 -23
  16. package/src/lib/agent-workspace-sync.ts +54 -10
  17. package/src/lib/capability-cloud-presence.ts +179 -0
  18. package/src/lib/capability-cloud-refresh.ts +43 -21
  19. package/src/lib/capability-cloud-sync.ts +165 -8
  20. package/src/lib/capability-selection.ts +62 -0
  21. package/src/lib/capability-workspace.ts +6 -0
  22. package/src/lib/game-client.ts +10 -0
  23. package/src/lib/hub-client.ts +75 -0
  24. package/src/lib/persona.ts +14 -1
  25. package/src/pipeline/event-hints.ts +1 -1
  26. package/src/runtime/clawclaw/owner.ts +25 -4
  27. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +107 -0
  28. package/src/runtime/clawclaw/plugins/mailbox/index.ts +1 -0
  29. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +12 -0
  30. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +10 -3
  31. package/src/runtime/game-sync-protocol.ts +47 -0
  32. package/src/runtime/ws-client.ts +7 -0
@@ -0,0 +1,179 @@
1
+ import type { AuthProfile } from './auth.js';
2
+ import type { LocalAgentWorkspaceSnapshot } from './agent-workspace-sync.js';
3
+ import type { WorkspaceResourceSummary } from './hub-client.js';
4
+ import {
5
+ readCapabilityWorkspaceRegistry,
6
+ writeCapabilityWorkspaceRegistry,
7
+ type CapabilityWorkspaceEntry,
8
+ type CapabilityWorkspaceType,
9
+ } from './capability-workspace.js';
10
+
11
+ export type CapabilityCloudStatus = 'workspace_missing';
12
+ export type CapabilityDeactivationReason = CapabilityCloudStatus | 'unequipped';
13
+
14
+ export interface CapabilityPresenceChange {
15
+ type: CapabilityWorkspaceType;
16
+ id: string;
17
+ resource_id: string;
18
+ reason?: CapabilityDeactivationReason;
19
+ }
20
+
21
+ export interface CapabilityPresenceResult {
22
+ deactivated: CapabilityPresenceChange[];
23
+ restored: CapabilityPresenceChange[];
24
+ inactiveResourceIds: string[];
25
+ }
26
+
27
+ function publisher(item: WorkspaceResourceSummary): 'official' | 'self' | 'community' {
28
+ if (item.owner.isOfficial) return 'official';
29
+ return item.isCreatedByMe ? 'self' : 'community';
30
+ }
31
+
32
+ function setCloudStatus(entry: CapabilityWorkspaceEntry, status: CapabilityCloudStatus | undefined): boolean {
33
+ if (!entry.hub || entry.hub.cloudStatus === status) return false;
34
+ if (status) entry.hub.cloudStatus = status;
35
+ else delete entry.hub.cloudStatus;
36
+ return true;
37
+ }
38
+
39
+ export function reconcileCapabilityWorkspacePresence(
40
+ workspaceDir: string,
41
+ profile: Pick<AuthProfile, 'apiKey'>,
42
+ inventory: readonly WorkspaceResourceSummary[],
43
+ snapshot?: LocalAgentWorkspaceSnapshot,
44
+ ): CapabilityPresenceResult {
45
+ const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
46
+ const selected = snapshot ? new Set(Object.values(snapshot.items).flat().map(item => item.resourceId)) : undefined;
47
+ const inventoryByResource = new Map(inventory.map(item => [item.resourceId, {
48
+ ...item, equipped: selected ? selected.has(item.resourceId) : item.equipped,
49
+ }]));
50
+ const deactivated: CapabilityPresenceChange[] = [];
51
+ const restored: CapabilityPresenceChange[] = [];
52
+ const inactiveResourceIds = new Set(
53
+ [...inventoryByResource.values()].filter((item) => !item.equipped).map((item) => item.resourceId),
54
+ );
55
+ let changed = false;
56
+ for (const entry of Object.values(registry.entries)) {
57
+ if (!entry.hub || entry.runtimeId === 'clawclaw') continue;
58
+ let entryChanged = false;
59
+ const item = inventoryByResource.get(entry.hub.resourceId);
60
+ const wasEquipped = entry.selection === 'equipped';
61
+ const nextStatus: CapabilityCloudStatus | undefined = item ? undefined : 'workspace_missing';
62
+ if (nextStatus) inactiveResourceIds.add(entry.hub.resourceId);
63
+
64
+ if (setCloudStatus(entry, nextStatus)) {
65
+ entryChanged = true;
66
+ if (nextStatus && wasEquipped) {
67
+ deactivated.push({
68
+ type: entry.type,
69
+ id: entry.runtimeId,
70
+ resource_id: entry.hub.resourceId,
71
+ reason: nextStatus,
72
+ });
73
+ }
74
+ }
75
+
76
+ if (item) {
77
+ const nextPublisher = publisher(item);
78
+ if (entry.hub.workspaceItemId !== item.workspaceItemId || entry.hub.publisher !== nextPublisher) {
79
+ entry.hub.workspaceItemId = item.workspaceItemId;
80
+ entry.hub.publisher = nextPublisher;
81
+ entryChanged = true;
82
+ }
83
+ }
84
+
85
+ if (nextStatus) {
86
+ if (entry.selection !== 'unequipped') {
87
+ entry.selection = 'unequipped';
88
+ entryChanged = true;
89
+ }
90
+ if (entry.conflictChoice) {
91
+ delete entry.conflictChoice;
92
+ entryChanged = true;
93
+ }
94
+ } else if (item) {
95
+ const nextSelection = item.equipped ? 'equipped'
96
+ : entry.selection === 'pending' ? 'pending' : 'unequipped';
97
+ if (entry.selection !== nextSelection) {
98
+ entry.selection = nextSelection;
99
+ entryChanged = true;
100
+ if (wasEquipped && !item.equipped) {
101
+ deactivated.push({
102
+ type: entry.type,
103
+ id: entry.runtimeId,
104
+ resource_id: entry.hub.resourceId,
105
+ reason: 'unequipped',
106
+ });
107
+ } else if (!wasEquipped && item.equipped) {
108
+ restored.push({
109
+ type: entry.type,
110
+ id: entry.runtimeId,
111
+ resource_id: entry.hub.resourceId,
112
+ });
113
+ }
114
+ }
115
+ }
116
+ if (entryChanged) {
117
+ entry.updatedAt = new Date().toISOString();
118
+ changed = true;
119
+ }
120
+ }
121
+ // Cloud-backed entries use the cloud choice; a default false on a newly
122
+ // uploaded item is not evidence that the player answered the first prompt.
123
+ if (changed) writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
124
+ return {
125
+ deactivated,
126
+ restored,
127
+ inactiveResourceIds: [...inactiveResourceIds],
128
+ };
129
+ }
130
+
131
+ export function filterInactiveAgentWorkspaceSnapshot(
132
+ workspaceDir: string,
133
+ profile: Pick<AuthProfile, 'apiKey'>,
134
+ snapshot: LocalAgentWorkspaceSnapshot | undefined,
135
+ additionalResourceIds: readonly string[] = [],
136
+ ): LocalAgentWorkspaceSnapshot | undefined {
137
+ if (!snapshot) return undefined;
138
+ const inactive = new Set(additionalResourceIds);
139
+ for (const entry of Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)) {
140
+ if (
141
+ entry.hub
142
+ && (entry.hub.cloudStatus || entry.selection !== 'equipped')
143
+ ) inactive.add(entry.hub.resourceId);
144
+ }
145
+ if (inactive.size === 0) return snapshot;
146
+ const filtered = structuredClone(snapshot);
147
+ for (const type of Object.keys(filtered.items) as Array<keyof typeof filtered.items>) {
148
+ filtered.items[type] = filtered.items[type].filter((item) => !inactive.has(item.resourceId)) as never;
149
+ }
150
+ return filtered;
151
+ }
152
+
153
+ /** A successful loadout remains authoritative even when the backpack endpoint
154
+ * is offline. Absence here means unequipped, not deleted. */
155
+ export function reconcileCapabilityLoadout(
156
+ workspaceDir: string,
157
+ profile: Pick<AuthProfile, 'apiKey'>,
158
+ snapshot: LocalAgentWorkspaceSnapshot,
159
+ ): CapabilityPresenceResult {
160
+ const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
161
+ const selected = new Set(Object.values(snapshot.items).flat().map(item => item.resourceId));
162
+ const result: CapabilityPresenceResult = { deactivated: [], restored: [], inactiveResourceIds: [] };
163
+ let changed = false;
164
+ for (const entry of Object.values(registry.entries)) {
165
+ if (!entry.hub || entry.runtimeId === 'clawclaw') continue;
166
+ const equipped = selected.has(entry.hub.resourceId);
167
+ if (!equipped) result.inactiveResourceIds.push(entry.hub.resourceId);
168
+ const selection = equipped ? 'equipped' : entry.selection === 'pending' ? 'pending' : 'unequipped';
169
+ if (selection !== entry.selection) {
170
+ const change = { type: entry.type, id: entry.runtimeId, resource_id: entry.hub.resourceId };
171
+ if (equipped) result.restored.push(change);
172
+ else if (entry.selection === 'equipped') result.deactivated.push({ ...change, reason: 'unequipped' });
173
+ entry.selection = selection;
174
+ changed = true;
175
+ }
176
+ }
177
+ if (changed) writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
178
+ return result;
179
+ }
@@ -80,6 +80,8 @@ export interface InstalledCapabilityUpdateResult {
80
80
  workspace_item_id: string;
81
81
  error: string;
82
82
  }>;
83
+ inventory: Awaited<ReturnType<HubClient['listWorkspace']>>['items'];
84
+ inventoryComplete: boolean;
83
85
  }
84
86
 
85
87
  export async function syncInstalledCapabilityUpdates(
@@ -87,30 +89,36 @@ export async function syncInstalledCapabilityUpdates(
87
89
  dependencies: CapabilityCloudRefreshDependencies = {},
88
90
  ): Promise<InstalledCapabilityUpdateResult> {
89
91
  const client = dependencies.client ?? HubClient.fromProfile(profile);
90
- const result: InstalledCapabilityUpdateResult = { updated: [], failed: [] };
92
+ const result: InstalledCapabilityUpdateResult = {
93
+ updated: [], failed: [], inventory: [], inventoryComplete: false,
94
+ };
91
95
  let cursor: string | undefined;
92
96
  do {
93
97
  const page = await client.listWorkspace({ cursor, limit: 100 });
94
- for (const item of page.items.filter((candidate) => candidate.hasUpdate)) {
95
- try {
96
- const synced = await client.syncWorkspaceItem(item.workspaceItemId);
97
- result.updated.push({
98
- type: item.resourceType,
99
- resource_id: item.resourceId,
100
- workspace_item_id: item.workspaceItemId,
101
- version_id: synced.versionId,
102
- });
103
- } catch (error) {
104
- result.failed.push({
105
- type: item.resourceType,
106
- resource_id: item.resourceId,
107
- workspace_item_id: item.workspaceItemId,
108
- error: error instanceof Error ? error.message : String(error),
109
- });
110
- }
111
- }
98
+ result.inventory.push(...page.items);
112
99
  cursor = page.hasMore && page.nextCursor ? page.nextCursor : undefined;
113
100
  } while (cursor);
101
+ for (const item of result.inventory.filter((candidate) => candidate.hasUpdate)) {
102
+ try {
103
+ const synced = await client.syncWorkspaceItem(item.workspaceItemId);
104
+ item.versionId = synced.versionId;
105
+ item.hasUpdate = false;
106
+ result.updated.push({
107
+ type: item.resourceType,
108
+ resource_id: item.resourceId,
109
+ workspace_item_id: item.workspaceItemId,
110
+ version_id: synced.versionId,
111
+ });
112
+ } catch (error) {
113
+ result.failed.push({
114
+ type: item.resourceType,
115
+ resource_id: item.resourceId,
116
+ workspace_item_id: item.workspaceItemId,
117
+ error: error instanceof Error ? error.message : String(error),
118
+ });
119
+ }
120
+ }
121
+ result.inventoryComplete = true;
114
122
  return result;
115
123
  }
116
124
 
@@ -226,7 +234,12 @@ export async function refreshCapabilitiesFromCloud(
226
234
  const result: CapabilityCloudRefreshResult = { downloaded: [], conflicts: [], failed: [], unchanged: [] };
227
235
  const active = activeResourceIds(activeWorkspace);
228
236
  const entries = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
229
- .filter((entry) => entry.runtimeId !== 'clawclaw' && entry.hub && !active.has(entry.hub.resourceId));
237
+ .filter((entry) => (
238
+ entry.runtimeId !== 'clawclaw'
239
+ && entry.hub
240
+ && !entry.hub.cloudStatus
241
+ && !active.has(entry.hub.resourceId)
242
+ ));
230
243
  for (const entry of entries) {
231
244
  const hub = entry.hub!;
232
245
  const type = resourceType(entry.type);
@@ -242,9 +255,17 @@ export async function refreshCapabilitiesFromCloud(
242
255
  }
243
256
  const detail = await client.getResource(type, hub.resourceId, workspaceItemId);
244
257
  if (detail.versionId === hub.versionId) {
245
- if (hub.observedCloudVersionId) updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
258
+ if (
259
+ hub.observedCloudVersionId
260
+ || (hub.localOriginUnrecognized && (
261
+ before === hub.baseSha256 || before === hub.lastUploadedSha256
262
+ ))
263
+ ) updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
246
264
  ...hub,
247
265
  observedCloudVersionId: undefined,
266
+ localOriginUnrecognized: before === hub.baseSha256 || before === hub.lastUploadedSha256
267
+ ? undefined
268
+ : hub.localOriginUnrecognized,
248
269
  });
249
270
  result.unchanged.push({ type: entry.type, id: entry.runtimeId });
250
271
  continue;
@@ -289,6 +310,7 @@ export async function refreshCapabilitiesFromCloud(
289
310
  baseSha256: artifact.digest,
290
311
  lastUploadedSha256: artifact.digest,
291
312
  observedCloudVersionId: undefined,
313
+ localOriginUnrecognized: undefined,
292
314
  });
293
315
  result.downloaded.push({
294
316
  type: entry.type,
@@ -1,16 +1,20 @@
1
1
  import {
2
+ existsSync,
2
3
  lstatSync,
3
4
  readFileSync,
5
+ realpathSync,
4
6
  readdirSync,
5
7
  } from 'node:fs';
6
- import { basename, extname, join, relative } from 'node:path';
8
+ import { basename, dirname, extname, join, relative } from 'node:path';
7
9
  import { createHash } from 'node:crypto';
10
+ import { ApiError } from './http-transport.js';
8
11
  import type { AuthProfile } from './auth.js';
9
12
  import {
10
13
  capabilityWorkspacePath,
11
14
  readCapabilityWorkspaceRegistry,
12
15
  updateCapabilityHubIdentity,
13
16
  setCapabilityConflictChoice,
17
+ classifyStrategyLifecycle,
14
18
  type CapabilityWorkspaceEntry,
15
19
  type CapabilityWorkspaceType,
16
20
  } from './capability-workspace.js';
@@ -21,7 +25,14 @@ import {
21
25
  type ResourceType,
22
26
  } from './hub-client.js';
23
27
  import type { LocalAgentWorkspaceSnapshot } from './agent-workspace-sync.js';
28
+ import { readSkillName } from './skill-host.js';
24
29
  import { createStoredZip, zipContentDigest, type ZipStoreEntry } from './zip-store.js';
30
+ import {
31
+ inspectClawclawBehaviorSource,
32
+ } from '../runtime/clawclaw/plugins/behavior/behavior-source.js';
33
+ import {
34
+ listClawclawPerceptionSourcesInDirectory,
35
+ } from '../runtime/clawclaw/plugins/perception/perception-source.js';
25
36
 
26
37
  export interface CapabilityCloudSyncChange {
27
38
  type: CapabilityWorkspaceType;
@@ -42,14 +53,22 @@ export interface CapabilityCloudSyncConflict {
42
53
  export interface CapabilityCloudSyncFailure {
43
54
  type: CapabilityWorkspaceType;
44
55
  id: string;
45
- action: 'create' | 'version' | 'fork';
56
+ action: 'create' | 'version' | 'fork' | 'equipment';
46
57
  error: string;
47
58
  }
48
59
 
60
+ export interface CapabilityCloudSyncSkip {
61
+ type: CapabilityWorkspaceType;
62
+ id: string;
63
+ reason: 'local_origin_unrecognized';
64
+ }
65
+
49
66
  export interface CapabilityCloudSyncResult {
67
+ equipmentChanged?: boolean;
50
68
  uploaded: CapabilityCloudSyncChange[];
51
69
  conflicts: CapabilityCloudSyncConflict[];
52
70
  failed: CapabilityCloudSyncFailure[];
71
+ skipped: CapabilityCloudSyncSkip[];
53
72
  unchanged: Array<{ type: CapabilityWorkspaceType; id: string }>;
54
73
  }
55
74
 
@@ -60,6 +79,12 @@ interface CapabilityCloudClient {
60
79
  installResource(resourceId: string): ReturnType<HubClient['installResource']>;
61
80
  getResource(type: ResourceType, id: string): ReturnType<HubClient['getResource']>;
62
81
  findWorkspaceItem(type: ResourceType, resourceId: string): ReturnType<HubClient['findWorkspaceItem']>;
82
+ updateWorkspaceEquipment(
83
+ workspaceItemId: string,
84
+ equipped: boolean,
85
+ ): ReturnType<HubClient['updateWorkspaceEquipment']>;
86
+ updateWorkspaceLoadout(input: Parameters<HubClient['updateWorkspaceLoadout']>[0]):
87
+ ReturnType<HubClient['updateWorkspaceLoadout']>;
63
88
  }
64
89
 
65
90
  export interface CapabilityCloudSyncDependencies {
@@ -67,6 +92,31 @@ export interface CapabilityCloudSyncDependencies {
67
92
  entryKeys?: readonly string[];
68
93
  }
69
94
 
95
+ async function updateCloudEquipment(
96
+ client: CapabilityCloudClient,
97
+ type: CapabilityWorkspaceType,
98
+ workspaceItemId: string,
99
+ equipped: boolean,
100
+ ): Promise<void> {
101
+ if (type === 'persona' && equipped) {
102
+ await client.updateWorkspaceLoadout({
103
+ personaItemIds: [workspaceItemId],
104
+ });
105
+ return;
106
+ }
107
+ await client.updateWorkspaceEquipment(workspaceItemId, equipped);
108
+ }
109
+
110
+ function nextPatchVersion(version: string): string {
111
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
112
+ if (!match) throw new Error(`capability_cloud_version_invalid:${version}`);
113
+ return `${match[1]}.${match[2]}.${BigInt(match[3]!) + 1n}`;
114
+ }
115
+
116
+ function unavailableForkSource(error: unknown): boolean {
117
+ return error instanceof ApiError && error.status === 404;
118
+ }
119
+
70
120
  function resourceType(type: CapabilityWorkspaceType): ResourceType {
71
121
  return type === 'behavior' ? 'strategy' : type;
72
122
  }
@@ -138,6 +188,44 @@ function snapshotResolution(
138
188
  .find((item) => item.resourceId === resourceId)?.resolution;
139
189
  }
140
190
 
191
+ const MAX_CAPABILITY_UPLOAD_BYTES = 10 * 1024 * 1024;
192
+
193
+ function validateUploadPayload(
194
+ entry: CapabilityWorkspaceEntry,
195
+ path: string,
196
+ payload: ReturnType<typeof uploadPayload>,
197
+ ): void {
198
+ const totalBytes = payload.source.reduce((total, file) => total + file.bytes.length, 0);
199
+ if (totalBytes > MAX_CAPABILITY_UPLOAD_BYTES) {
200
+ throw new Error('capability_validation_failed:content_too_large');
201
+ }
202
+ if (entry.type === 'behavior') {
203
+ const source = inspectClawclawBehaviorSource(path, dirname(path));
204
+ if (!source || source.id !== entry.runtimeId) {
205
+ throw new Error('capability_validation_failed:behavior_invalid');
206
+ }
207
+ return;
208
+ }
209
+ if (entry.type === 'perception') {
210
+ const resolvedPath = realpathSync(path);
211
+ const source = listClawclawPerceptionSourcesInDirectory(dirname(path))
212
+ .find((candidate) => realpathSync(candidate.sourcePath) === resolvedPath);
213
+ if (!source || source.id !== entry.runtimeId) {
214
+ throw new Error('capability_validation_failed:perception_invalid');
215
+ }
216
+ return;
217
+ }
218
+ if (entry.type === 'persona') {
219
+ if (!existsSync(path) || extname(path).toLowerCase() !== '.md') {
220
+ throw new Error('capability_validation_failed:persona_invalid');
221
+ }
222
+ return;
223
+ }
224
+ if (readSkillName(path) !== entry.runtimeId) {
225
+ throw new Error('capability_validation_failed:skill_invalid');
226
+ }
227
+ }
228
+
141
229
  export async function syncCapabilitiesToCloud(
142
230
  workspaceDir: string,
143
231
  profile: Pick<AuthProfile, 'apiKey' | 'serverUrl'>,
@@ -149,14 +237,25 @@ export async function syncCapabilitiesToCloud(
149
237
  uploaded: [],
150
238
  conflicts: [],
151
239
  failed: [],
240
+ skipped: [],
152
241
  unchanged: [],
153
242
  };
154
243
  const selectedKeys = dependencies.entryKeys ? new Set(dependencies.entryKeys) : undefined;
155
244
  const entries = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
156
245
  .filter((entry) => (
157
- entry.runtimeId !== 'clawclaw' && (!selectedKeys || selectedKeys.has(entry.key))
246
+ entry.runtimeId !== 'clawclaw'
247
+ && !entry.hub?.cloudStatus
248
+ && (!selectedKeys || selectedKeys.has(entry.key))
158
249
  ));
159
250
  for (const entry of entries) {
251
+ if (entry.hub?.pendingEquipment !== undefined) {
252
+ // An old request must never replay over a newer Hub selection. The player
253
+ // can retry equip explicitly; load always consumes the latest cloud state.
254
+ updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
255
+ ...entry.hub, pendingEquipment: undefined,
256
+ });
257
+ delete entry.hub.pendingEquipment;
258
+ }
160
259
  if (entry.hub?.pendingBackpackRestoreResourceId) {
161
260
  try {
162
261
  await client.installResource(entry.hub.pendingBackpackRestoreResourceId);
@@ -166,6 +265,9 @@ export async function syncCapabilitiesToCloud(
166
265
  });
167
266
  delete entry.hub.pendingBackpackRestoreResourceId;
168
267
  } catch (error) {
268
+ if (unavailableForkSource(error)) updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
269
+ ...entry.hub, pendingBackpackRestoreResourceId: undefined,
270
+ });
169
271
  result.failed.push({
170
272
  type: entry.type,
171
273
  id: entry.runtimeId,
@@ -188,6 +290,20 @@ export async function syncCapabilitiesToCloud(
188
290
  });
189
291
  continue;
190
292
  }
293
+ if (
294
+ (
295
+ entry.hub?.localOriginUnrecognized
296
+ || (entry.hub && snapshotResolution(snapshot, entry.hub.resourceId) === 'local_origin_unrecognized')
297
+ )
298
+ && entry.conflictChoice !== 'local'
299
+ ) {
300
+ result.skipped.push({
301
+ type: entry.type,
302
+ id: entry.runtimeId,
303
+ reason: 'local_origin_unrecognized',
304
+ });
305
+ continue;
306
+ }
191
307
  if (
192
308
  entry.hub?.observedCloudVersionId
193
309
  && entry.hub.observedCloudVersionId !== entry.hub.versionId
@@ -221,6 +337,9 @@ export async function syncCapabilitiesToCloud(
221
337
  const action = entry.hub?.publisher === 'self' ? 'version' : entry.hub ? 'fork' : 'create';
222
338
  try {
223
339
  let baseVersionId = entry.hub?.versionId;
340
+ let versionNumber: string | undefined;
341
+ const strategyKind = entry.type === 'behavior'
342
+ ? classifyStrategyLifecycle(readFileSync(path, 'utf8')) : undefined;
224
343
  if (action === 'version' && entry.hub) {
225
344
  const latest = await client.getResource(resourceType(entry.type), entry.hub.resourceId);
226
345
  if (latest.versionId !== entry.hub.versionId && entry.conflictChoice !== 'local') {
@@ -233,7 +352,9 @@ export async function syncCapabilitiesToCloud(
233
352
  continue;
234
353
  }
235
354
  baseVersionId = latest.versionId;
355
+ versionNumber = nextPatchVersion(latest.versionNumber ?? '1.0.0');
236
356
  }
357
+ validateUploadPayload(entry, path, payload);
237
358
  const uploadedSource = await client.uploadFiles(sourceFileType(entry.type), payload.source);
238
359
  let packageFileId: string | undefined;
239
360
  if (payload.packageUpload) {
@@ -247,6 +368,8 @@ export async function syncCapabilitiesToCloud(
247
368
  ? await client.createPrivateVersion({
248
369
  resourceId: entry.hub.resourceId,
249
370
  baseVersionId,
371
+ versionNumber: versionNumber!,
372
+ strategyKind,
250
373
  title: entry.title,
251
374
  description: entry.description,
252
375
  sourceFiles: uploadedSource,
@@ -254,20 +377,21 @@ export async function syncCapabilitiesToCloud(
254
377
  })
255
378
  : await client.createPrivateResource({
256
379
  resourceType: resourceType(entry.type),
380
+ strategyKind,
257
381
  title: entry.title,
258
382
  description: entry.description,
259
383
  sourceFiles: uploadedSource,
260
384
  packageFileId,
261
385
  forkFromWorkspaceItemId: action === 'fork' ? entry.hub?.workspaceItemId : undefined,
262
386
  });
263
- const workspaceItem = mutation.workspaceItemId
264
- ? undefined
265
- : await client.findWorkspaceItem(resourceType(entry.type), mutation.resourceId);
266
- const workspaceItemId = mutation.workspaceItemId ?? workspaceItem?.workspaceItemId;
387
+ // Persist the server-confirmed resource before any further network request.
388
+ // A failed backpack lookup must not turn the next load into another create.
389
+ let workspaceItemId = mutation.workspaceItemId
390
+ ?? (action === 'version' ? entry.hub?.workspaceItemId : undefined);
267
391
  const updatedHubIdentity = {
268
392
  resourceId: mutation.resourceId,
269
393
  versionId: mutation.versionId,
270
- ...(workspaceItemId ? { workspaceItemId } : {}),
394
+ workspaceItemId,
271
395
  publisher: 'self',
272
396
  baseSha256: payload.digest,
273
397
  lastUploadedSha256: payload.digest,
@@ -286,14 +410,47 @@ export async function syncCapabilitiesToCloud(
286
410
  version_id: mutation.versionId,
287
411
  ...(workspaceItemId ? { workspace_item_id: workspaceItemId } : {}),
288
412
  });
413
+ if (!workspaceItemId) {
414
+ try {
415
+ const item = await client.findWorkspaceItem(resourceType(entry.type), mutation.resourceId);
416
+ if (!item) throw new Error('capability_cloud_workspace_item_missing');
417
+ workspaceItemId = item.workspaceItemId;
418
+ updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
419
+ ...updatedHubIdentity, workspaceItemId,
420
+ });
421
+ result.uploaded.at(-1)!.workspace_item_id = workspaceItemId;
422
+ } catch (error) {
423
+ result.failed.push({ type: entry.type, id: entry.runtimeId, action: 'equipment',
424
+ error: `resource_created_workspace_lookup_failed:${error instanceof Error ? error.message : String(error)}` });
425
+ }
426
+ }
427
+ if (action === 'create' && entry.origin === 'local' && entry.selection !== 'pending' && workspaceItemId) {
428
+ try {
429
+ await updateCloudEquipment(client, entry.type, workspaceItemId, entry.selection === 'equipped');
430
+ result.equipmentChanged = true;
431
+ } catch (error) {
432
+ result.failed.push({
433
+ type: entry.type,
434
+ id: entry.runtimeId,
435
+ action: 'equipment',
436
+ error: `capability_cloud_equipment_sync_failed:${
437
+ error instanceof Error ? error.message : String(error)
438
+ }`,
439
+ });
440
+ }
441
+ }
289
442
  if (action === 'fork' && entry.hub) {
290
443
  try {
291
444
  await client.installResource(entry.hub.resourceId);
292
445
  updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
293
446
  ...updatedHubIdentity,
447
+ workspaceItemId,
294
448
  pendingBackpackRestoreResourceId: undefined,
295
449
  });
296
450
  } catch (error) {
451
+ if (unavailableForkSource(error)) updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
452
+ ...updatedHubIdentity, workspaceItemId, pendingBackpackRestoreResourceId: undefined,
453
+ });
297
454
  result.failed.push({
298
455
  type: entry.type,
299
456
  id: entry.runtimeId,
@@ -0,0 +1,62 @@
1
+ import type { AuthProfile } from './auth.js';
2
+ import { HubClient } from './hub-client.js';
3
+ import { readCapabilityWorkspaceRegistry, writeCapabilityWorkspaceRegistry,
4
+ type CapabilityWorkspaceType } from './capability-workspace.js';
5
+ import { updateGameplayConfig } from './gameplay-config.js';
6
+
7
+ export type EquipmentClient = Pick<HubClient,
8
+ 'updateWorkspaceEquipment' | 'updateWorkspaceLoadout' | 'findWorkspaceItem'>;
9
+
10
+ /** One selection path for all currently exposed Agent commands. Cloud failures
11
+ * leave local selection untouched; a confirmed cloud choice is not rolled back
12
+ * using a possibly stale local snapshot. */
13
+ export async function selectCapability(
14
+ workspaceDir: string,
15
+ profile: Pick<AuthProfile, 'apiKey' | 'serverUrl'>,
16
+ type: CapabilityWorkspaceType,
17
+ id: string,
18
+ equipped: boolean,
19
+ providedClient?: EquipmentClient,
20
+ ) {
21
+ const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
22
+ const matches = Object.values(registry.entries).filter(entry => entry.type === type && entry.runtimeId === id);
23
+ const local = matches.filter(entry => entry.origin === 'local');
24
+ const candidates = local.length ? local : matches;
25
+ if (candidates.length !== 1) throw new Error(`capability_selection_${candidates.length ? 'ambiguous' : 'not_found'}:${type}:${id}`);
26
+ const entry = candidates[0]!;
27
+ if (entry.hub) {
28
+ const client = providedClient ?? HubClient.fromProfile(profile);
29
+ if (entry.hub.cloudStatus) throw new Error(`capability_workspace_removed:${type}/${id}`);
30
+ let itemId = entry.hub.workspaceItemId;
31
+ if (!itemId) {
32
+ const item = await client.findWorkspaceItem(type === 'behavior' ? 'strategy' : type, entry.hub.resourceId);
33
+ if (!item) throw new Error(`capability_cloud_workspace_item_missing:${type}/${id}`);
34
+ itemId = item.workspaceItemId;
35
+ }
36
+ if (type === 'persona' && equipped) {
37
+ await client.updateWorkspaceLoadout({ personaItemIds: [itemId] });
38
+ } else {
39
+ await client.updateWorkspaceEquipment(itemId, equipped);
40
+ }
41
+ entry.hub.workspaceItemId = itemId;
42
+ delete entry.hub.pendingEquipment;
43
+ }
44
+ if (type === 'persona' && equipped) {
45
+ for (const other of Object.values(registry.entries)) {
46
+ if (other.type === 'persona' && other.key !== entry.key && other.selection === 'equipped') {
47
+ other.selection = 'unequipped';
48
+ }
49
+ }
50
+ }
51
+ entry.selection = equipped ? 'equipped' : 'unequipped';
52
+ entry.updatedAt = new Date().toISOString();
53
+ writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
54
+ if (type === 'behavior' || type === 'perception') {
55
+ updateGameplayConfig(config => {
56
+ const field = type === 'behavior' ? 'disabled_behaviors' : 'disabled_perception_modules';
57
+ config[field] = config[field].filter(value => value !== id);
58
+ if (!equipped && !entry.hub) config[field].push(id);
59
+ }, workspaceDir, profile);
60
+ }
61
+ return entry;
62
+ }
@@ -28,7 +28,13 @@ export interface CapabilityHubIdentity {
28
28
  baseSha256?: string;
29
29
  lastUploadedSha256?: string;
30
30
  pendingBackpackRestoreResourceId?: string;
31
+ /** Retry a local equipment choice after the cloud resource itself was created successfully. */
32
+ pendingEquipment?: boolean;
31
33
  observedCloudVersionId?: string;
34
+ /** The working copy existed before CCL had a trustworthy Hub baseline. */
35
+ localOriginUnrecognized?: boolean;
36
+ /** Cloud association is retained locally but automatic cloud I/O is suspended. */
37
+ cloudStatus?: 'workspace_missing';
32
38
  }
33
39
 
34
40
  export interface CapabilityWorkspaceEntry {