@myclaw163/clawclaw-cli 0.8.16 → 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.
@@ -11,6 +11,7 @@ import {
11
11
  getUserDataAccountPerceptionsDir,
12
12
  } from '../lib/user-data.js';
13
13
  import { readLocalAgentWorkspaceSnapshot } from '../lib/agent-workspace-sync.js';
14
+ import { filterInactiveAgentWorkspaceSnapshot } from '../lib/capability-cloud-presence.js';
14
15
  import {
15
16
  listAgentWorkspacePerceptionSources,
16
17
  mergeAgentWorkspacePerceptionSources,
@@ -18,7 +19,8 @@ import {
18
19
  import { PERCEPTION_PLUGIN_API_VERSION } from '../sdk/perception-plugin/index.js';
19
20
  import { pluginApiVersionStatus } from '../runtime/clawclaw/plugins/plugin-api-version.js';
20
21
  import { discoverLocalCapabilities } from '../lib/capability-discovery.js';
21
- import { capabilityEntryForPath, setCapabilitySelection } from '../lib/capability-workspace.js';
22
+ import { capabilityEntryForPath, readCapabilityWorkspaceRegistry } from '../lib/capability-workspace.js';
23
+ import { selectCapability } from '../lib/capability-selection.js';
22
24
 
23
25
  export interface PerceptionCommandDependencies {
24
26
  activeProfile?: () => AuthProfile | null;
@@ -56,23 +58,25 @@ Perception modules:
56
58
  const workspaceDir = getWorkspaceDir();
57
59
  const profile = activeProfile(dependencies);
58
60
  ensureAccountUserDataLayout(workspaceDir, profile);
59
- const snapshot = readLocalAgentWorkspaceSnapshot(workspaceDir, profile);
61
+ const snapshot = filterInactiveAgentWorkspaceSnapshot(
62
+ workspaceDir,
63
+ profile,
64
+ readLocalAgentWorkspaceSnapshot(workspaceDir, profile),
65
+ );
60
66
  const hub = snapshot
61
67
  ? listAgentWorkspacePerceptionSources(workspaceDir, profile, snapshot)
62
68
  : [];
63
69
  const hubIds = new Set(hub.map(({ id }) => id));
64
70
  const local = discoverLocalCapabilities(workspaceDir, profile).perceptions
71
+ .filter(({ entry }) => !snapshot?.items.perception.some(item => item.resourceId === entry.hub?.resourceId))
65
72
  .map(({ source }) => source);
66
- if ((opts.disable && hubIds.has(opts.disable)) || (opts.enable && hubIds.has(opts.enable))) {
67
- throw new Error(`Hub Perception '${opts.disable ?? opts.enable}' enablement is controlled by the Hub loadout.`);
68
- }
73
+ const registered = (id: string) => Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
74
+ .some(entry => entry.type === 'perception' && entry.runtimeId === id);
69
75
  if (opts.disable) {
70
76
  const source = local.find(({ id }) => id === opts.disable);
71
- if (!source) throw new Error(`Unknown local Perception '${opts.disable}'.`);
72
- setCapabilitySelection(workspaceDir, profile, 'perception', opts.disable, false);
73
- const updated = updateGameplayConfig((current) => {
74
- current.disabled_perception_modules.push(opts.disable!);
75
- }, workspaceDir, profile);
77
+ if (!source && !hubIds.has(opts.disable) && !registered(opts.disable)) throw new Error(`Unknown local Perception '${opts.disable}'.`);
78
+ await selectCapability(workspaceDir, profile, 'perception', opts.disable, false);
79
+ const updated = readGameplayConfig(workspaceDir, profile);
76
80
  console.log(JSON.stringify({
77
81
  perception_module: opts.disable,
78
82
  disabled: true,
@@ -84,12 +88,9 @@ Perception modules:
84
88
  }
85
89
  if (opts.enable) {
86
90
  const source = local.find(({ id }) => id === opts.enable);
87
- if (!source) throw new Error(`Unknown local Perception '${opts.enable}'.`);
88
- setCapabilitySelection(workspaceDir, profile, 'perception', opts.enable, true);
89
- const updated = updateGameplayConfig((current) => {
90
- current.disabled_perception_modules = current.disabled_perception_modules
91
- .filter((id) => id !== opts.enable);
92
- }, workspaceDir, profile);
91
+ if (!source && !hubIds.has(opts.enable) && !registered(opts.enable)) throw new Error(`Unknown local Perception '${opts.enable}'.`);
92
+ await selectCapability(workspaceDir, profile, 'perception', opts.enable, true);
93
+ const updated = readGameplayConfig(workspaceDir, profile);
93
94
  console.log(JSON.stringify({
94
95
  perception_module: opts.enable,
95
96
  disabled: false,
@@ -15,6 +15,10 @@ import {
15
15
  import { loadPersonaSnapshot } from '../lib/load-context.js';
16
16
  import { discoverLocalCapabilities } from '../lib/capability-discovery.js';
17
17
  import { setCapabilitySelection } from '../lib/capability-workspace.js';
18
+ import { readCapabilityWorkspaceRegistry, writeCapabilityWorkspaceRegistry } from '../lib/capability-workspace.js';
19
+ import { selectCapability } from '../lib/capability-selection.js';
20
+ import { HubClient } from '../lib/hub-client.js';
21
+ import { readLocalAgentWorkspaceSnapshot } from '../lib/agent-workspace-sync.js';
18
22
 
19
23
  function context() {
20
24
  const profile = new AuthStore().getActive();
@@ -60,11 +64,11 @@ export function createPersonaCommand(): Command {
60
64
  persona
61
65
  .command('create <name>')
62
66
  .description('Create and select an empty account-local Persona preset')
63
- .action((name: string) => {
67
+ .action(async (name: string) => {
64
68
  const { directory, workspaceDir, profile } = context();
65
69
  const created = createPersonaPreset(name, directory);
66
70
  discoverLocalCapabilities(workspaceDir, profile);
67
- setCapabilitySelection(workspaceDir, profile, 'persona', created.id, true);
71
+ await selectCapability(workspaceDir, profile, 'persona', created.id, true);
68
72
  writePersonaSelection(workspaceDir, profile, { source: 'local', id: created.id });
69
73
  console.log(JSON.stringify({
70
74
  path: created.path,
@@ -75,16 +79,16 @@ export function createPersonaCommand(): Command {
75
79
  persona
76
80
  .command('use <preset>')
77
81
  .description('Select an account-local Persona preset')
78
- .action((presetName: string) => {
82
+ .action(async (presetName: string) => {
79
83
  const { directory, workspaceDir, profile } = context();
80
84
  const found = findPersonaPreset(presetName, directory);
81
85
  if (!found) {
82
86
  const available = listPersonaPresets(directory).map(p => p.name).join(', ') || 'none';
83
87
  throw new Error(`Persona preset "${presetName}" not found. Available: ${available}`);
84
88
  }
85
- writePersonaSelection(workspaceDir, profile, { source: 'local', id: found.id });
86
89
  discoverLocalCapabilities(workspaceDir, profile);
87
- setCapabilitySelection(workspaceDir, profile, 'persona', found.id, true);
90
+ const entry = await selectCapability(workspaceDir, profile, 'persona', found.id, true);
91
+ writePersonaSelection(workspaceDir, profile, entry.hub ? { source: 'hub' } : { source: 'local', id: found.id });
88
92
  console.log(JSON.stringify({
89
93
  path: found.path,
90
94
  preset: { id: found.id, name: found.name, source: 'local' },
@@ -97,6 +101,11 @@ export function createPersonaCommand(): Command {
97
101
  .description('Use the Persona selected by the active account Hub loadout')
98
102
  .action(() => {
99
103
  const { workspaceDir, profile } = context();
104
+ const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
105
+ for (const entry of Object.values(registry.entries)) {
106
+ if (entry.type === 'persona' && !entry.hub && entry.selection === 'equipped') entry.selection = 'unequipped';
107
+ }
108
+ writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
100
109
  writePersonaSelection(workspaceDir, profile, { source: 'hub' });
101
110
  console.log(JSON.stringify(resolveActivePersonaFile(), null, 2));
102
111
  });
@@ -104,8 +113,17 @@ export function createPersonaCommand(): Command {
104
113
  persona
105
114
  .command('clear')
106
115
  .description('Use no Persona for the active account')
107
- .action(() => {
116
+ .action(async () => {
108
117
  const { workspaceDir, profile } = context();
118
+ const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
119
+ if (Object.values(registry.entries).some(entry => entry.type === 'persona' && entry.hub)
120
+ || readLocalAgentWorkspaceSnapshot(workspaceDir, profile)?.items.persona.length) {
121
+ await HubClient.fromProfile(profile).updateWorkspaceLoadout({ personaItemIds: [] });
122
+ }
123
+ for (const entry of Object.values(registry.entries)) {
124
+ if (entry.type === 'persona') entry.selection = 'unequipped';
125
+ }
126
+ writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
109
127
  writePersonaSelection(workspaceDir, profile, { source: 'none' });
110
128
  console.log(JSON.stringify({ path: null, source: 'none' }, null, 2));
111
129
  });
@@ -17,6 +17,8 @@ export interface AgentWorkspaceRemoteItem {
17
17
  workspace_item_id: string;
18
18
  resource_id: string;
19
19
  version_id: string;
20
+ version_number?: string;
21
+ version_description?: string;
20
22
  resource_type: ResourceType;
21
23
  workspace_kind: 'owned' | 'installed';
22
24
  is_created_by_me: boolean;
@@ -44,6 +44,8 @@ export interface AgentWorkspaceBehaviorManagement {
44
44
  workspaceItemId?: string;
45
45
  resourceId?: string;
46
46
  versionId?: string;
47
+ versionNumber?: string;
48
+ versionDescription?: string;
47
49
  resolution?: LocalAgentWorkspaceSnapshot['items']['strategy'][number]['resolution'];
48
50
  ownerId?: string;
49
51
  ownerName?: string | null;
@@ -74,7 +76,8 @@ export function listAgentWorkspaceBehaviorSources(
74
76
  : []
75
77
  )),
76
78
  );
77
- const sources = listClawclawBehaviorSources(root).map((source) => {
79
+ const sources = listClawclawBehaviorSources(root)
80
+ .filter(source => itemByPath.has(realpathSync(source.sourcePath))).map((source) => {
78
81
  const item = itemByPath.get(realpathSync(source.sourcePath));
79
82
  if (!item) throw new Error(`agent_workspace_behavior_metadata_missing:${source.id}`);
80
83
  const trusted = item.sourceFiles[0]
@@ -91,6 +94,8 @@ export function listAgentWorkspaceBehaviorSources(
91
94
  workspaceItemId: item.workspaceItemId,
92
95
  resourceId: item.resourceId,
93
96
  versionId: item.versionId,
97
+ versionNumber: item.versionNumber,
98
+ versionDescription: item.versionDescription,
94
99
  resolution: item.resolution,
95
100
  ...(item.hub?.ownerId ? { ownerId: item.hub.ownerId } : {}),
96
101
  ...(item.hub ? { ownerName: item.hub.ownerName } : {}),
@@ -109,7 +114,10 @@ export function listAgentWorkspacePerceptionSources(
109
114
  const active = currentSnapshot(workspaceDir, profile, snapshot);
110
115
  if (!active || active.items.perception.length === 0) return [];
111
116
  const root = join(localAgentWorkspaceSnapshotRoot(workspaceDir, profile, active), 'runtime', 'perceptions');
112
- const sources = existsSync(root) ? listClawclawPerceptionSourcesInDirectory(root) : [];
117
+ const selectedPaths = new Set(active.items.perception.filter(item => item.runtimeEntryPath)
118
+ .map(item => resolveLocalAgentWorkspacePath(workspaceDir, profile, active, item.runtimeEntryPath!)));
119
+ const sources = existsSync(root) ? listClawclawPerceptionSourcesInDirectory(root)
120
+ .filter(source => selectedPaths.has(source.sourcePath)) : [];
113
121
  const ids = new Set<string>();
114
122
  for (const source of sources) {
115
123
  if (ids.has(source.id)) throw new Error(`AGENT_RESOURCE_ID_CONFLICT:perception:${source.id}`);
@@ -152,11 +152,15 @@ function unique(values: Array<string | undefined>): string[] {
152
152
  function accountManagedSkillSources(
153
153
  workspaceDir: string,
154
154
  profile: Pick<AuthProfile, 'apiKey'>,
155
+ includeInactive = false,
155
156
  ): Map<string, string> {
156
157
  const skillsRoot = getUserDataAccountSkillsDir(workspaceDir, profile);
157
158
  const sources = new Map<string, string>();
158
159
  for (const [name] of Object.entries(readManifest(workspaceDir, profile).entries)) {
159
160
  if (name === 'clawclaw') continue;
161
+ const entry = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
162
+ .find(entry => entry.type === 'skill' && entry.runtimeId === name);
163
+ if (!includeInactive && entry && (entry.selection !== 'equipped' || entry.hub?.cloudStatus)) continue;
160
164
  sources.set(name, join(skillsRoot, name));
161
165
  }
162
166
  for (const entry of Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)) {
@@ -186,7 +190,7 @@ export function switchActiveAccountSkillLinks(
186
190
  const linkTarget = dependencies.linkTarget ?? linkAgentSkillTarget;
187
191
  const unlinkTarget = dependencies.unlinkTarget ?? unlinkAgentSkillTarget;
188
192
  const previous = previousProfile
189
- ? accountManagedSkillSources(workspaceDir, previousProfile)
193
+ ? accountManagedSkillSources(workspaceDir, previousProfile, true)
190
194
  : new Map<string, string>();
191
195
  const next = accountManagedSkillSources(workspaceDir, nextProfile);
192
196
 
@@ -298,6 +302,7 @@ export function syncAgentWorkspaceSkills(
298
302
  }
299
303
  const path = capabilityWorkspacePath(workspaceDir, profile, entry);
300
304
  if (desired.has(entry.runtimeId)) {
305
+ if (entry.hub?.resourceId === desired.get(entry.runtimeId)?.resourceId) continue;
301
306
  failed.push({ name: entry.runtimeId, action: 'add', error: 'local and Hub Skill names conflict' });
302
307
  continue;
303
308
  }
@@ -473,6 +478,7 @@ export function syncAgentWorkspaceSkills(
473
478
  }
474
479
  }
475
480
  if (!failedRemoval) removed.push(name);
481
+ else next.entries[name] = current.entries[name]!;
476
482
  }
477
483
 
478
484
  writeManifest(workspaceDir, profile, next);
@@ -34,6 +34,10 @@ import {
34
34
  capabilityEntryForHubResource,
35
35
  capabilityWorkspacePath,
36
36
  } from './capability-workspace.js';
37
+ import { inspectClawclawBehaviorSource, behaviorSourceCompatibilityError } from '../runtime/clawclaw/plugins/behavior/behavior-source.js';
38
+ import { listClawclawPerceptionSourcesInDirectory } from '../runtime/clawclaw/plugins/perception/perception-source.js';
39
+ import { BEHAVIOR_PLUGIN_API_VERSION } from '../sdk/behavior-plugin/index.js';
40
+ import { PERCEPTION_PLUGIN_API_VERSION } from '../sdk/perception-plugin/index.js';
37
41
 
38
42
  const RESOURCE_TYPES: readonly ResourceType[] = ['skill', 'strategy', 'persona', 'perception'];
39
43
  const SHA256 = /^[0-9a-f]{64}$/;
@@ -52,6 +56,8 @@ export interface LocalAgentWorkspaceItem {
52
56
  workspaceItemId: string;
53
57
  resourceId: string;
54
58
  versionId: string;
59
+ versionNumber?: string;
60
+ versionDescription?: string;
55
61
  resourceType: ResourceType;
56
62
  hub?: {
57
63
  workspaceKind: 'owned' | 'installed';
@@ -354,6 +360,8 @@ async function materializeItem(
354
360
  workspaceItemId: item.workspace_item_id,
355
361
  resourceId: item.resource_id,
356
362
  versionId: item.version_id,
363
+ versionNumber: item.version_number,
364
+ versionDescription: item.version_description,
357
365
  resourceType: item.resource_type,
358
366
  hub: {
359
367
  workspaceKind: item.workspace_kind,
@@ -608,7 +616,7 @@ function inspectLocalSnapshot(
608
616
  const modifiedAtMs = statSync(workingPath).mtimeMs;
609
617
  item.resolution = item.resolution === 'local_origin_unrecognized'
610
618
  ? 'local_origin_unrecognized'
611
- : 'local_modified';
619
+ : item.resolution === 'concurrent_difference' ? 'concurrent_difference' : 'local_modified';
612
620
  item.localContentDigest = localDigest;
613
621
  item.localModifiedAtMs = modifiedAtMs;
614
622
  if (projectionSha !== localSha) projectionOutdated = true;
@@ -679,8 +687,15 @@ export async function syncAgentWorkspaceConfig(
679
687
  const client = dependencies.client ?? new AgentWorkspaceClient(profile);
680
688
  const remote = await client.getConfig();
681
689
  validateRemoteConfig(remote);
690
+ const contentUnchanged = previous && RESOURCE_TYPES.every(type => {
691
+ const items = previous.items[type];
692
+ return items.length === remote.items[type].length && remote.items[type].every(item =>
693
+ items.some(old => old.resourceId === item.resource_id && old.versionId === item.version_id
694
+ && old.workspaceItemId === item.workspace_item_id && old.contentDigest === item.content_digest));
695
+ });
682
696
  if (
683
697
  previous?.revision === remote.revision
698
+ && contentUnchanged
684
699
  && previous.metadataVersion === 1
685
700
  && previous.layoutVersion === 3
686
701
  && inspected?.projectionOutdated !== true
@@ -709,11 +724,12 @@ export async function syncAgentWorkspaceConfig(
709
724
  );
710
725
  for (const type of RESOURCE_TYPES) {
711
726
  for (const item of remote.items[type]) {
712
- const materialized = await materializeItem(
713
- temporary,
714
- item,
715
- dependencies.download ?? downloadAgentWorkspaceFile,
716
- );
727
+ let materialized: LocalAgentWorkspaceItem;
728
+ try {
729
+ materialized = await materializeItem(temporary, item, dependencies.download ?? downloadAgentWorkspaceFile);
730
+ } catch (error) {
731
+ throw new Error(`agent_workspace_resource_failed:${type}:${item.resource_id}:${item.source_files.map(file => file.relative_path).join(',')}:${error instanceof Error ? error.message : String(error)}`);
732
+ }
717
733
  const prior = previousByKey.get(type)?.get(materialized.resourceId);
718
734
  let workingPath: string | undefined;
719
735
  let persistedWorkingMetadata: WorkingCopyMetadata | undefined;
@@ -786,7 +802,7 @@ export async function syncAgentWorkspaceConfig(
786
802
  );
787
803
  materialized.resolution = !override.originRecognized
788
804
  ? 'local_origin_unrecognized'
789
- : remoteAdvancedFromLocalBaseline
805
+ : remoteAdvancedFromLocalBaseline || prior?.resolution === 'concurrent_difference'
790
806
  ? 'concurrent_difference'
791
807
  : 'local_modified';
792
808
  materialized.localContentDigest = override.contentDigest;
@@ -800,6 +816,22 @@ export async function syncAgentWorkspaceConfig(
800
816
  ));
801
817
  }
802
818
  }
819
+ // Reject an invalid cloud replacement before touching the working copy
820
+ // or pointer. Invalid local edits remain visible to load diagnostics.
821
+ if (prior && materialized.resolution === 'hub' && materialized.runtimeEntryPath) {
822
+ const path = join(temporary, materialized.runtimeEntryPath);
823
+ if (type === 'strategy') {
824
+ const source = inspectClawclawBehaviorSource(path, dirname(path));
825
+ if (!source || source.apiVersion !== BEHAVIOR_PLUGIN_API_VERSION || behaviorSourceCompatibilityError(source)) {
826
+ throw new Error(`agent_workspace_resource_failed:strategy:${item.resource_id}:cloud_module_invalid`);
827
+ }
828
+ } else if (type === 'perception') {
829
+ const source = listClawclawPerceptionSourcesInDirectory(dirname(path)).find(source => source.sourcePath === path);
830
+ if (!source || source.apiVersion !== PERCEPTION_PLUGIN_API_VERSION) {
831
+ throw new Error(`agent_workspace_resource_failed:perception:${item.resource_id}:cloud_module_invalid`);
832
+ }
833
+ }
834
+ }
803
835
  if (materialized.workingCopyPath && effectiveBytes) {
804
836
  const accountRoot = getUserDataAccountDir(workspaceDir, profile);
805
837
  workingUpdates.push({
@@ -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);