@myclaw163/clawclaw-cli 0.8.12 → 0.8.14

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 (68) hide show
  1. package/docs/configuration.md +11 -12
  2. package/docs/custom-modules/README.md +3 -3
  3. package/docs/custom-modules/behavior.md +1 -1
  4. package/docs/custom-modules/perception.md +1 -1
  5. package/docs/custom-modules/trigger.md +1 -1
  6. package/docs/runtime/official-perception-modules.md +1 -1
  7. package/package.json +1 -1
  8. package/scripts/check-skill-command-surface.mjs +1 -0
  9. package/scripts/sync-bundled-skill.mjs +89 -52
  10. package/skills/clawclaw/SKILL.md +10 -6
  11. package/skills/clawclaw/references/BEHAVIORS.md +2 -0
  12. package/skills/clawclaw/references/CHANNELS.md +1 -1
  13. package/skills/clawclaw/references/COMMANDS.md +11 -4
  14. package/skills/clawclaw/references/HUB.md +4 -2
  15. package/skills/clawclaw/references/STREAM.md +4 -2
  16. package/src/cli.ts +2 -0
  17. package/src/commands/behavior.ts +49 -8
  18. package/src/commands/capability.ts +345 -0
  19. package/src/commands/load.ts +195 -8
  20. package/src/commands/perception.ts +21 -7
  21. package/src/commands/persona.ts +6 -0
  22. package/src/commands/trigger.ts +8 -5
  23. package/src/lib/agent-workspace-skills.ts +167 -68
  24. package/src/lib/agent-workspace-sync.ts +20 -31
  25. package/src/lib/capability-cloud-refresh.ts +313 -0
  26. package/src/lib/capability-cloud-sync.ts +315 -0
  27. package/src/lib/capability-discovery.ts +94 -0
  28. package/src/lib/capability-workspace.ts +291 -0
  29. package/src/lib/game-client.ts +12 -4
  30. package/src/lib/hub-client.ts +131 -4
  31. package/src/lib/persona.ts +1 -24
  32. package/src/lib/skill-host.ts +63 -0
  33. package/src/lib/user-data.ts +47 -59
  34. package/src/lib/zip-store.ts +92 -0
  35. package/src/pipeline/event-format.ts +5 -0
  36. package/src/pipeline/event-hints.ts +10 -0
  37. package/src/runtime/clawclaw/agent-event-policy.ts +2 -0
  38. package/src/runtime/clawclaw/behavior-input.ts +5 -0
  39. package/src/runtime/clawclaw/owner.ts +12 -12
  40. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +150 -18
  41. package/src/runtime/clawclaw/plugins/behavior/behavior-action.ts +8 -0
  42. package/src/runtime/clawclaw/plugins/behavior/behavior-decision-history.ts +88 -0
  43. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +173 -11
  44. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +6 -0
  45. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +3 -1
  46. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +5 -1
  47. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +5 -5
  48. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +213 -6
  49. package/src/runtime/clawclaw/plugins/source/game-transport.ts +29 -4
  50. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +153 -0
  51. package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
  52. package/src/runtime/clawclaw/runtime.ts +31 -3
  53. package/src/runtime/clawclaw-event-catalog.ts +2 -0
  54. package/src/runtime/framework/events/event-repository.ts +1 -1
  55. package/src/runtime/framework/events/memory-event-repository.ts +59 -1
  56. package/src/runtime/framework/events/sqlite-event-repository.ts +23 -1
  57. package/src/runtime/framework/mailbox/types.ts +2 -0
  58. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +58 -0
  59. package/src/runtime/framework/persistence/memory-first-persistence.ts +380 -0
  60. package/src/runtime/framework/plugins/contracts.ts +2 -2
  61. package/src/runtime/framework/plugins/runtime-input-journal.ts +173 -17
  62. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +23 -11
  63. package/src/runtime/framework/runtime.ts +57 -4
  64. package/src/runtime/framework/state/history/contracts.ts +9 -1
  65. package/src/runtime/framework/state/history/memory-state-history-repository.ts +49 -7
  66. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +16 -0
  67. package/src/sdk/behavior-plugin/index.ts +5 -24
  68. package/src/sdk/module-input/index.ts +47 -0
@@ -16,7 +16,6 @@ import {
16
16
  import { BEHAVIOR_PLUGIN_API_VERSION, type BehaviorActivationLayer } from '../sdk/behavior-plugin/index.js';
17
17
  import {
18
18
  behaviorSourceCompatibilityError,
19
- listClawclawBehaviorSources,
20
19
  } from '../runtime/clawclaw/plugins/behavior/behavior-source.js';
21
20
  import { readLocalAgentWorkspaceSnapshot } from '../lib/agent-workspace-sync.js';
22
21
  import {
@@ -34,6 +33,13 @@ import {
34
33
  type CommandIo,
35
34
  type ShortCommandOperationResult,
36
35
  } from '../short-command/runner.js';
36
+ import { discoverLocalCapabilities } from '../lib/capability-discovery.js';
37
+ import {
38
+ capabilityEntryForPath,
39
+ classifyStrategyLifecycle,
40
+ setCapabilitySelection,
41
+ } from '../lib/capability-workspace.js';
42
+ import { readFileSync } from 'node:fs';
37
43
 
38
44
  const OWNER_CONTROL_TIMEOUT_MS = 30_000;
39
45
  const MAX_BEHAVIOR_RUNTIME_MS = 120_000;
@@ -115,6 +121,7 @@ function sourceEntry(
115
121
  inputs: source.inputs,
116
122
  produces: source.produces ?? [],
117
123
  ...(source.runtime === undefined ? {} : { runtime: source.runtime }),
124
+ strategy_type: classifyStrategyLifecycle(readFileSync(source.sourcePath, 'utf8')),
118
125
  source: source.management.source,
119
126
  managed_by: source.management.managedBy,
120
127
  ...(source.management.publisher ? { publisher: source.management.publisher } : {}),
@@ -265,19 +272,23 @@ function activeProfile(dependencies: BehaviorCommandDependencies): AuthProfile {
265
272
  function discoveredSources(profile: Pick<AuthProfile, 'apiKey'>) {
266
273
  const workspaceDir = getWorkspaceDir();
267
274
  ensureAccountUserDataLayout(workspaceDir, profile);
268
- const local = listClawclawBehaviorSources(getUserDataAccountBehaviorsDir(workspaceDir, profile));
275
+ const localCapabilities = discoverLocalCapabilities(workspaceDir, profile).behaviors;
276
+ const local = localCapabilities.map(({ source }) => source);
277
+ const selectedLocal = localCapabilities
278
+ .filter(({ entry }) => entry.selection === 'equipped')
279
+ .map(({ source }) => source);
269
280
  const snapshot = readLocalAgentWorkspaceSnapshot(workspaceDir, profile);
270
281
  const hub = snapshot
271
282
  ? listAgentWorkspaceBehaviorSources(workspaceDir, profile, snapshot)
272
283
  : [];
273
- return { local, hub };
284
+ return { local, selectedLocal, hub };
274
285
  }
275
286
 
276
287
  function sources(
277
288
  profile: Pick<AuthProfile, 'apiKey'>,
278
289
  disabledLocalIds: ReadonlySet<string> = new Set(),
279
290
  ): readonly ManagedClawclawBehaviorSource[] {
280
- const { local, hub } = discoveredSources(profile);
291
+ const { selectedLocal: local, hub } = discoveredSources(profile);
281
292
  return mergeAgentWorkspaceBehaviorSources(
282
293
  local.filter(({ id }) => !disabledLocalIds.has(id)),
283
294
  hub,
@@ -288,14 +299,25 @@ function inventorySources(
288
299
  profile: Pick<AuthProfile, 'apiKey'>,
289
300
  disabledLocalIds: ReadonlySet<string>,
290
301
  ): readonly ManagedClawclawBehaviorSource[] {
291
- const { local, hub } = discoveredSources(profile);
302
+ const { local, selectedLocal, hub } = discoveredSources(profile);
292
303
  const effective = mergeAgentWorkspaceBehaviorSources(
293
- local.filter(({ id }) => !disabledLocalIds.has(id)),
304
+ selectedLocal.filter(({ id }) => !disabledLocalIds.has(id)),
294
305
  hub,
295
306
  );
296
307
  const effectiveIds = new Set(effective.map(({ id }) => id));
297
308
  const disabledOnly = mergeAgentWorkspaceBehaviorSources(
298
- local.filter(({ id }) => disabledLocalIds.has(id) && !effectiveIds.has(id)),
309
+ local.filter((source) => (
310
+ !effectiveIds.has(source.id)
311
+ && (
312
+ disabledLocalIds.has(source.id)
313
+ || capabilityEntryForPath(
314
+ getWorkspaceDir(),
315
+ profile,
316
+ 'behavior',
317
+ source.sourcePath,
318
+ )?.selection !== 'equipped'
319
+ )
320
+ )),
299
321
  [],
300
322
  );
301
323
  return [...effective, ...disabledOnly];
@@ -310,7 +332,7 @@ export function createBehaviorCommand(dependencies: BehaviorCommandDependencies
310
332
  const profile = (dependencies.activeProfile ?? (() => new AuthStore().getActive()))();
311
333
  const directory = profile
312
334
  ? getUserDataAccountBehaviorsDir(workspaceDir, profile)
313
- : '<active-account>/behaviors/local';
335
+ : '<active-account>/capabilities/behaviors';
314
336
  return `\nBehavior modules:\n Place .ts or .js files in ${directory}\n Discovery reads static manifests without executing module code.\n`;
315
337
  });
316
338
 
@@ -321,6 +343,14 @@ export function createBehaviorCommand(dependencies: BehaviorCommandDependencies
321
343
  const profile = activeProfile(dependencies);
322
344
  const gameplay = readGameplayConfig(workspaceDir, profile);
323
345
  const disabled = new Set(gameplay.disabled_behaviors);
346
+ for (const source of discoveredSources(profile).local) {
347
+ if (capabilityEntryForPath(
348
+ workspaceDir,
349
+ profile,
350
+ 'behavior',
351
+ source.sourcePath,
352
+ )?.selection !== 'equipped') disabled.add(source.id);
353
+ }
324
354
  const discovered = inventorySources(profile, disabled);
325
355
  const entries = discovered.map((source) => sourceEntry(source, disabled));
326
356
  console.log(JSON.stringify({
@@ -339,6 +369,14 @@ export function createBehaviorCommand(dependencies: BehaviorCommandDependencies
339
369
  const profile = activeProfile(dependencies);
340
370
  const gameplay = readGameplayConfig(workspaceDir, profile);
341
371
  const disabled = new Set(gameplay.disabled_behaviors);
372
+ for (const source of discoveredSources(profile).local) {
373
+ if (capabilityEntryForPath(
374
+ workspaceDir,
375
+ profile,
376
+ 'behavior',
377
+ source.sourcePath,
378
+ )?.selection !== 'equipped') disabled.add(source.id);
379
+ }
342
380
  const source = inventorySources(profile, disabled).find((candidate) => candidate.id === id);
343
381
  if (!source) throw new Error(`Unknown behavior module '${id}'.`);
344
382
  console.log(JSON.stringify({
@@ -377,6 +415,9 @@ export function createBehaviorCommand(dependencies: BehaviorCommandDependencies
377
415
  );
378
416
  }
379
417
  }
418
+ if (local) {
419
+ setCapabilitySelection(workspaceDir, profile, 'behavior', id, !disabled);
420
+ }
380
421
  const updated = updateGameplayConfig((current) => {
381
422
  current.disabled_behaviors = disabled
382
423
  ? [...current.disabled_behaviors, id]
@@ -0,0 +1,345 @@
1
+ import { Command, InvalidArgumentError } from 'commander';
2
+ import { AuthStore, type AuthProfile } from '../lib/auth.js';
3
+ import { discoverLocalCapabilities } from '../lib/capability-discovery.js';
4
+ import {
5
+ capabilityWorkspacePath,
6
+ pendingCapabilitySelections,
7
+ readCapabilityWorkspaceRegistry,
8
+ saveCapabilityDirectoryDraft,
9
+ saveCapabilityDraft,
10
+ setCapabilitySelection,
11
+ setCapabilityConflictChoice,
12
+ updateCapabilityHubIdentity,
13
+ type CapabilityWorkspaceEntry,
14
+ type CapabilityWorkspaceType,
15
+ } from '../lib/capability-workspace.js';
16
+ import { getWorkspaceDir } from '../lib/init-command.js';
17
+ import { writePersonaSelection } from '../lib/persona.js';
18
+ import {
19
+ agentSkillTargets,
20
+ findSkillRoot,
21
+ linkAgentSkillTarget,
22
+ overwriteAgentSkillTarget,
23
+ unlinkAgentSkillTarget,
24
+ type SkillHostMutationResult,
25
+ } from '../lib/skill-host.js';
26
+ import { HubClient, type ResourceType } from '../lib/hub-client.js';
27
+ import { unzip } from '../lib/hub-unzip.js';
28
+ import { zipContentDigest } from '../lib/zip-store.js';
29
+ import { createHash, randomUUID } from 'node:crypto';
30
+ import { tmpdir } from 'node:os';
31
+ import { dirname, extname, isAbsolute, join, relative, resolve as resolvePath } from 'node:path';
32
+ import {
33
+ existsSync,
34
+ mkdirSync,
35
+ mkdtempSync,
36
+ readFileSync,
37
+ readdirSync,
38
+ renameSync,
39
+ rmSync,
40
+ writeFileSync,
41
+ } from 'node:fs';
42
+ import {
43
+ readLocalAgentWorkspaceSnapshot,
44
+ resolveLocalAgentWorkspaceSnapshot,
45
+ } from '../lib/agent-workspace-sync.js';
46
+ import { syncCapabilitiesToCloud } from '../lib/capability-cloud-sync.js';
47
+
48
+ interface CapabilityResolveCloudClient {
49
+ getResource(type: ResourceType, id: string, workspaceItemId?: string): ReturnType<HubClient['getResource']>;
50
+ downloadArtifact(type: ResourceType, id: string, workspaceItemId?: string): ReturnType<HubClient['downloadArtifact']>;
51
+ }
52
+
53
+ export interface CapabilityCommandDependencies {
54
+ client?: CapabilityResolveCloudClient;
55
+ cloudSync?: typeof syncCapabilitiesToCloud;
56
+ skillTargets?: (name: string) => readonly string[];
57
+ linkSkillTarget?: (sourcePath: string, targetPath: string) => SkillHostMutationResult;
58
+ unlinkSkillTarget?: (targetPath: string) => SkillHostMutationResult;
59
+ }
60
+
61
+ function pathInside(root: string, candidate: string): boolean {
62
+ const child = relative(resolvePath(root), resolvePath(candidate));
63
+ return child === '' || (!child.startsWith('..') && !isAbsolute(child));
64
+ }
65
+
66
+ function writeCloudFileAtomically(target: string, bytes: Buffer): void {
67
+ const stage = `${target}.ccl-stage-${randomUUID()}`;
68
+ const displaced = `${target}.ccl-old-${randomUUID()}`;
69
+ let moved = false;
70
+ try {
71
+ mkdirSync(dirname(target), { recursive: true });
72
+ writeFileSync(stage, bytes);
73
+ if (existsSync(target)) {
74
+ renameSync(target, displaced);
75
+ moved = true;
76
+ }
77
+ renameSync(stage, target);
78
+ if (moved) rmSync(displaced, { force: true });
79
+ } catch (error) {
80
+ rmSync(stage, { force: true });
81
+ if (moved && !existsSync(target) && existsSync(displaced)) {
82
+ try { renameSync(displaced, target); } catch { /* retain displaced recovery copy */ }
83
+ }
84
+ throw error;
85
+ }
86
+ }
87
+
88
+ function cloudSkillStage(archive: Buffer): { root: string; stage: string; digest: string } {
89
+ const stage = mkdtempSync(join(tmpdir(), 'ccl-capability-cloud-skill-'));
90
+ try {
91
+ for (const entry of unzip(archive)) {
92
+ const target = resolvePath(stage, ...entry.path.split('/'));
93
+ if (!pathInside(stage, target) || target === resolvePath(stage)) {
94
+ throw new Error('capability_cloud_skill_path_invalid');
95
+ }
96
+ mkdirSync(dirname(target), { recursive: true });
97
+ writeFileSync(target, entry.content);
98
+ }
99
+ const root = findSkillRoot(stage);
100
+ if (!existsSync(join(root, 'SKILL.md'))) throw new Error('capability_cloud_skill_invalid');
101
+ const files: Array<{ path: string; content: Buffer }> = [];
102
+ const visit = (directory: string): void => {
103
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
104
+ const path = join(directory, entry.name);
105
+ if (entry.isDirectory()) visit(path);
106
+ else if (entry.isFile()) files.push({
107
+ path: relative(root, path).replaceAll('\\', '/'),
108
+ content: readFileSync(path),
109
+ });
110
+ }
111
+ };
112
+ visit(root);
113
+ return { root, stage, digest: zipContentDigest(files) };
114
+ } catch (error) {
115
+ rmSync(stage, { recursive: true, force: true });
116
+ throw error;
117
+ }
118
+ }
119
+
120
+ function activeProfile(): AuthProfile {
121
+ const profile = new AuthStore().getActive();
122
+ if (!profile) throw new Error('No active account. Run `ccl account register` or switch accounts first.');
123
+ return profile;
124
+ }
125
+
126
+ function parseRef(value: string): { type: CapabilityWorkspaceType; id: string } {
127
+ const match = /^(behavior|perception|persona|skill)\/(\S.{0,254})$/u.exec(value);
128
+ if (!match) {
129
+ throw new InvalidArgumentError('expected <behavior|perception|persona|skill>/<id>');
130
+ }
131
+ return { type: match[1] as CapabilityWorkspaceType, id: match[2]! };
132
+ }
133
+
134
+ function applySkillSelection(
135
+ entry: CapabilityWorkspaceEntry,
136
+ equipped: boolean,
137
+ workspaceDir: string,
138
+ profile: AuthProfile,
139
+ dependencies: CapabilityCommandDependencies,
140
+ ): void {
141
+ const source = capabilityWorkspacePath(workspaceDir, profile, entry);
142
+ const targets = dependencies.skillTargets ?? agentSkillTargets;
143
+ const link = dependencies.linkSkillTarget ?? linkAgentSkillTarget;
144
+ const unlink = dependencies.unlinkSkillTarget ?? unlinkAgentSkillTarget;
145
+ const applied: string[] = [];
146
+ for (const target of targets(entry.runtimeId)) {
147
+ const result = equipped ? link(source, target) : unlink(target);
148
+ if (!result.ok) {
149
+ for (const completed of applied.reverse()) {
150
+ if (equipped) unlink(completed);
151
+ else link(source, completed);
152
+ }
153
+ throw new Error(`capability_skill_${equipped ? 'equip' : 'unequip'}_failed:${
154
+ result.error ?? result.stderr?.trim() ?? 'skill host mutation failed'
155
+ }`);
156
+ }
157
+ applied.push(target);
158
+ }
159
+ }
160
+
161
+ function updateSelection(
162
+ ref: string,
163
+ equipped: boolean,
164
+ dependencies: CapabilityCommandDependencies,
165
+ ): Record<string, unknown> {
166
+ const workspaceDir = getWorkspaceDir();
167
+ const profile = activeProfile();
168
+ discoverLocalCapabilities(workspaceDir, profile);
169
+ const { type, id } = parseRef(ref);
170
+ if (type === 'skill') {
171
+ const matches = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
172
+ .filter((candidate) => (
173
+ candidate.type === type && candidate.runtimeId === id && candidate.origin === 'local'
174
+ ));
175
+ if (matches.length !== 1) {
176
+ throw new Error(`capability_selection_${matches.length === 0 ? 'not_found' : 'ambiguous'}:${type}:${id}`);
177
+ }
178
+ applySkillSelection(matches[0]!, equipped, workspaceDir, profile, dependencies);
179
+ }
180
+ const entry = setCapabilitySelection(workspaceDir, profile, type, id, equipped);
181
+ if (type === 'persona') {
182
+ writePersonaSelection(
183
+ workspaceDir,
184
+ profile,
185
+ equipped ? { source: 'local', id } : { source: 'none' },
186
+ );
187
+ }
188
+ return {
189
+ capability: `${type}/${id}`,
190
+ equipped,
191
+ selection: entry.selection,
192
+ effective: 'immediate',
193
+ reload_required_before_game: true,
194
+ };
195
+ }
196
+
197
+ export function createCapabilityCommand(dependencies: CapabilityCommandDependencies = {}): Command {
198
+ const capability = new Command('capability')
199
+ .alias('cap')
200
+ .description('Inspect and persist one-time local capability assembly choices');
201
+
202
+ capability.addCommand(new Command('pending')
203
+ .description('List newly discovered local capabilities awaiting one assembly choice')
204
+ .action(() => {
205
+ const workspaceDir = getWorkspaceDir();
206
+ const profile = activeProfile();
207
+ discoverLocalCapabilities(workspaceDir, profile);
208
+ console.log(JSON.stringify({ pending: pendingCapabilitySelections(workspaceDir, profile) }, null, 2));
209
+ }));
210
+
211
+ capability.addCommand(new Command('list')
212
+ .description('List persisted local capability assembly choices')
213
+ .action(() => {
214
+ const workspaceDir = getWorkspaceDir();
215
+ const profile = activeProfile();
216
+ discoverLocalCapabilities(workspaceDir, profile);
217
+ console.log(JSON.stringify({
218
+ capabilities: Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries),
219
+ }, null, 2));
220
+ }));
221
+
222
+ capability.addCommand(new Command('equip')
223
+ .argument('<type/id>', 'Local capability reference')
224
+ .allowExcessArguments(false)
225
+ .action((ref: string) => console.log(JSON.stringify(updateSelection(ref, true, dependencies), null, 2))));
226
+
227
+ capability.addCommand(new Command('unequip')
228
+ .argument('<type/id>', 'Local capability reference')
229
+ .allowExcessArguments(false)
230
+ .action((ref: string) => console.log(JSON.stringify(updateSelection(ref, false, dependencies), null, 2))));
231
+
232
+ capability.addCommand(new Command('resolve')
233
+ .description('Resolve one local/cloud content conflict')
234
+ .argument('<type/id>', 'Capability reference')
235
+ .requiredOption('--use <choice>', 'local | cloud | later')
236
+ .allowExcessArguments(false)
237
+ .action(async (ref: string, opts: { use: string }) => {
238
+ if (!['local', 'cloud', 'later'].includes(opts.use)) {
239
+ throw new InvalidArgumentError('--use must be local, cloud, or later');
240
+ }
241
+ const workspaceDir = getWorkspaceDir();
242
+ const profile = activeProfile();
243
+ const { type, id } = parseRef(ref);
244
+ const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
245
+ const matches = Object.values(registry.entries).filter((entry) => (
246
+ entry.type === type && entry.runtimeId === id && entry.hub
247
+ ));
248
+ if (matches.length !== 1) throw new Error(`capability_conflict_${matches.length === 0 ? 'not_found' : 'ambiguous'}:${ref}`);
249
+ const entry = matches[0]!;
250
+ if (opts.use === 'local') {
251
+ const storedSnapshot = readLocalAgentWorkspaceSnapshot(workspaceDir, profile);
252
+ if (!storedSnapshot) throw new Error(`capability_local_upload_requires_load:${ref}`);
253
+ const snapshot = resolveLocalAgentWorkspaceSnapshot(workspaceDir, profile, storedSnapshot);
254
+ setCapabilityConflictChoice(workspaceDir, profile, entry.key, 'local');
255
+ const synced = await (dependencies.cloudSync ?? syncCapabilitiesToCloud)(
256
+ workspaceDir,
257
+ profile,
258
+ snapshot,
259
+ { entryKeys: [entry.key] },
260
+ );
261
+ const uploaded = synced.uploaded.find((item) => item.type === type && item.id === id);
262
+ const unchanged = synced.unchanged.some((item) => item.type === type && item.id === id);
263
+ const conflict = synced.conflicts.find((item) => item.type === type && item.id === id);
264
+ const failures = synced.failed.filter((item) => item.type === type && item.id === id);
265
+ if (!uploaded && !unchanged) {
266
+ if (conflict) throw new Error(`capability_upload_conflict:${ref}`);
267
+ throw new Error(`capability_upload_failed:${ref}:${failures[0]?.error ?? 'unknown'}`);
268
+ }
269
+ console.log(JSON.stringify({
270
+ capability: ref,
271
+ resolution: 'local',
272
+ effective: 'immediate',
273
+ upload: uploaded ? {
274
+ status: 'completed',
275
+ action: uploaded.action,
276
+ resource_id: uploaded.resource_id,
277
+ version_id: uploaded.version_id,
278
+ } : { status: 'unchanged' },
279
+ ...(failures.length > 0 ? { warnings: failures.map(({ error }) => error) } : {}),
280
+ reload_required_before_game: true,
281
+ }, null, 2));
282
+ return;
283
+ }
284
+ if (opts.use === 'later') {
285
+ setCapabilityConflictChoice(workspaceDir, profile, entry.key, undefined);
286
+ console.log(JSON.stringify({
287
+ capability: ref,
288
+ resolution: 'deferred',
289
+ effective: 'current_local',
290
+ reload_required_before_game: false,
291
+ }, null, 2));
292
+ return;
293
+ }
294
+ if (!entry.hub) throw new Error(`capability_cloud_identity_missing:${ref}`);
295
+ const hubType = (type === 'behavior' ? 'strategy' : type) as ResourceType;
296
+ const client = dependencies.client ?? HubClient.fromProfile(profile);
297
+ const workspaceItemId = entry.hub.publisher === 'self' ? undefined : entry.hub.workspaceItemId;
298
+ const detail = await client.getResource(hubType, entry.hub.resourceId, workspaceItemId);
299
+ const cloudBytes = await client.downloadArtifact(hubType, entry.hub.resourceId, workspaceItemId);
300
+ const target = capabilityWorkspacePath(workspaceDir, profile, entry);
301
+ let draft: string;
302
+ let digest: string;
303
+ if (type === 'skill') {
304
+ const staged = cloudSkillStage(cloudBytes);
305
+ try {
306
+ draft = saveCapabilityDirectoryDraft(workspaceDir, profile, {
307
+ type,
308
+ runtimeId: id,
309
+ sourcePath: target,
310
+ });
311
+ const replaced = overwriteAgentSkillTarget(staged.root, target);
312
+ if (!replaced.ok) throw new Error(replaced.error ?? 'capability_cloud_restore_failed');
313
+ digest = staged.digest;
314
+ } finally {
315
+ rmSync(staged.stage, { recursive: true, force: true });
316
+ }
317
+ } else {
318
+ draft = saveCapabilityDraft(workspaceDir, profile, {
319
+ type,
320
+ runtimeId: id,
321
+ bytes: readFileSync(target),
322
+ extension: extname(target),
323
+ });
324
+ writeCloudFileAtomically(target, cloudBytes);
325
+ digest = createHash('sha256').update(cloudBytes).digest('hex');
326
+ }
327
+ updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
328
+ ...entry.hub,
329
+ versionId: detail.versionId,
330
+ baseSha256: digest,
331
+ lastUploadedSha256: digest,
332
+ observedCloudVersionId: undefined,
333
+ });
334
+ setCapabilityConflictChoice(workspaceDir, profile, entry.key, undefined);
335
+ console.log(JSON.stringify({
336
+ capability: ref,
337
+ resolution: 'cloud',
338
+ draft,
339
+ effective: 'immediate',
340
+ reload_required_before_game: true,
341
+ }, null, 2));
342
+ }));
343
+
344
+ return capability;
345
+ }