@myclaw163/clawclaw-cli 0.8.16 → 0.8.18
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.
- package/docs/configuration.md +7 -3
- package/docs/runtime/owner-lifecycle-and-observability.md +25 -0
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +22 -3
- package/skills/clawclaw/references/COMMANDS.md +8 -4
- package/src/commands/account.ts +9 -1
- package/src/commands/behavior.ts +17 -17
- package/src/commands/capability.ts +33 -25
- package/src/commands/load.ts +145 -8
- package/src/commands/perception.ts +17 -16
- package/src/commands/persona.ts +24 -6
- package/src/lib/agent-workspace-client.ts +2 -0
- package/src/lib/agent-workspace-runtime.ts +10 -2
- package/src/lib/agent-workspace-skills.ts +7 -1
- package/src/lib/agent-workspace-sync.ts +39 -7
- package/src/lib/capability-cloud-presence.ts +179 -0
- package/src/lib/capability-cloud-refresh.ts +33 -20
- package/src/lib/capability-cloud-sync.ts +94 -7
- package/src/lib/capability-selection.ts +62 -0
- package/src/lib/capability-workspace.ts +4 -0
- package/src/lib/game-client.ts +40 -10
- package/src/lib/http-transport.ts +2 -2
- package/src/lib/hub-client.ts +75 -0
- package/src/lib/persona.ts +14 -1
- package/src/pipeline/event-hints.ts +1 -1
- package/src/runtime/clawclaw/owner.ts +32 -20
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +33 -6
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +8 -0
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +25 -0
- package/src/runtime/framework/capability-registry.ts +31 -1
- package/src/runtime/framework/plugins/contracts.ts +2 -0
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +14 -4
- package/src/runtime/framework/runtime.ts +5 -0
- package/src/runtime/game-sync-ingress-protocol.ts +34 -0
- package/src/runtime/game-sync-ingress-worker.ts +153 -0
- package/src/runtime/observability/factory.ts +2 -1
- package/src/runtime/observability/process-timing.ts +59 -0
- package/src/runtime/threaded-ws-client.ts +196 -0
- package/src/runtime/ws-client.ts +48 -1
|
@@ -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 = {
|
|
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
|
-
|
|
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) =>
|
|
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);
|
|
@@ -7,12 +7,14 @@ import {
|
|
|
7
7
|
} from 'node:fs';
|
|
8
8
|
import { basename, dirname, extname, join, relative } from 'node:path';
|
|
9
9
|
import { createHash } from 'node:crypto';
|
|
10
|
+
import { ApiError } from './http-transport.js';
|
|
10
11
|
import type { AuthProfile } from './auth.js';
|
|
11
12
|
import {
|
|
12
13
|
capabilityWorkspacePath,
|
|
13
14
|
readCapabilityWorkspaceRegistry,
|
|
14
15
|
updateCapabilityHubIdentity,
|
|
15
16
|
setCapabilityConflictChoice,
|
|
17
|
+
classifyStrategyLifecycle,
|
|
16
18
|
type CapabilityWorkspaceEntry,
|
|
17
19
|
type CapabilityWorkspaceType,
|
|
18
20
|
} from './capability-workspace.js';
|
|
@@ -51,7 +53,7 @@ export interface CapabilityCloudSyncConflict {
|
|
|
51
53
|
export interface CapabilityCloudSyncFailure {
|
|
52
54
|
type: CapabilityWorkspaceType;
|
|
53
55
|
id: string;
|
|
54
|
-
action: 'create' | 'version' | 'fork';
|
|
56
|
+
action: 'create' | 'version' | 'fork' | 'equipment';
|
|
55
57
|
error: string;
|
|
56
58
|
}
|
|
57
59
|
|
|
@@ -62,6 +64,7 @@ export interface CapabilityCloudSyncSkip {
|
|
|
62
64
|
}
|
|
63
65
|
|
|
64
66
|
export interface CapabilityCloudSyncResult {
|
|
67
|
+
equipmentChanged?: boolean;
|
|
65
68
|
uploaded: CapabilityCloudSyncChange[];
|
|
66
69
|
conflicts: CapabilityCloudSyncConflict[];
|
|
67
70
|
failed: CapabilityCloudSyncFailure[];
|
|
@@ -76,6 +79,12 @@ interface CapabilityCloudClient {
|
|
|
76
79
|
installResource(resourceId: string): ReturnType<HubClient['installResource']>;
|
|
77
80
|
getResource(type: ResourceType, id: string): ReturnType<HubClient['getResource']>;
|
|
78
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']>;
|
|
79
88
|
}
|
|
80
89
|
|
|
81
90
|
export interface CapabilityCloudSyncDependencies {
|
|
@@ -83,6 +92,31 @@ export interface CapabilityCloudSyncDependencies {
|
|
|
83
92
|
entryKeys?: readonly string[];
|
|
84
93
|
}
|
|
85
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
|
+
|
|
86
120
|
function resourceType(type: CapabilityWorkspaceType): ResourceType {
|
|
87
121
|
return type === 'behavior' ? 'strategy' : type;
|
|
88
122
|
}
|
|
@@ -209,9 +243,19 @@ export async function syncCapabilitiesToCloud(
|
|
|
209
243
|
const selectedKeys = dependencies.entryKeys ? new Set(dependencies.entryKeys) : undefined;
|
|
210
244
|
const entries = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
|
|
211
245
|
.filter((entry) => (
|
|
212
|
-
entry.runtimeId !== 'clawclaw'
|
|
246
|
+
entry.runtimeId !== 'clawclaw'
|
|
247
|
+
&& !entry.hub?.cloudStatus
|
|
248
|
+
&& (!selectedKeys || selectedKeys.has(entry.key))
|
|
213
249
|
));
|
|
214
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
|
+
}
|
|
215
259
|
if (entry.hub?.pendingBackpackRestoreResourceId) {
|
|
216
260
|
try {
|
|
217
261
|
await client.installResource(entry.hub.pendingBackpackRestoreResourceId);
|
|
@@ -221,6 +265,9 @@ export async function syncCapabilitiesToCloud(
|
|
|
221
265
|
});
|
|
222
266
|
delete entry.hub.pendingBackpackRestoreResourceId;
|
|
223
267
|
} catch (error) {
|
|
268
|
+
if (unavailableForkSource(error)) updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
|
|
269
|
+
...entry.hub, pendingBackpackRestoreResourceId: undefined,
|
|
270
|
+
});
|
|
224
271
|
result.failed.push({
|
|
225
272
|
type: entry.type,
|
|
226
273
|
id: entry.runtimeId,
|
|
@@ -290,6 +337,9 @@ export async function syncCapabilitiesToCloud(
|
|
|
290
337
|
const action = entry.hub?.publisher === 'self' ? 'version' : entry.hub ? 'fork' : 'create';
|
|
291
338
|
try {
|
|
292
339
|
let baseVersionId = entry.hub?.versionId;
|
|
340
|
+
let versionNumber: string | undefined;
|
|
341
|
+
const strategyKind = entry.type === 'behavior'
|
|
342
|
+
? classifyStrategyLifecycle(readFileSync(path, 'utf8')) : undefined;
|
|
293
343
|
if (action === 'version' && entry.hub) {
|
|
294
344
|
const latest = await client.getResource(resourceType(entry.type), entry.hub.resourceId);
|
|
295
345
|
if (latest.versionId !== entry.hub.versionId && entry.conflictChoice !== 'local') {
|
|
@@ -302,6 +352,7 @@ export async function syncCapabilitiesToCloud(
|
|
|
302
352
|
continue;
|
|
303
353
|
}
|
|
304
354
|
baseVersionId = latest.versionId;
|
|
355
|
+
versionNumber = nextPatchVersion(latest.versionNumber ?? '1.0.0');
|
|
305
356
|
}
|
|
306
357
|
validateUploadPayload(entry, path, payload);
|
|
307
358
|
const uploadedSource = await client.uploadFiles(sourceFileType(entry.type), payload.source);
|
|
@@ -317,6 +368,8 @@ export async function syncCapabilitiesToCloud(
|
|
|
317
368
|
? await client.createPrivateVersion({
|
|
318
369
|
resourceId: entry.hub.resourceId,
|
|
319
370
|
baseVersionId,
|
|
371
|
+
versionNumber: versionNumber!,
|
|
372
|
+
strategyKind,
|
|
320
373
|
title: entry.title,
|
|
321
374
|
description: entry.description,
|
|
322
375
|
sourceFiles: uploadedSource,
|
|
@@ -324,20 +377,21 @@ export async function syncCapabilitiesToCloud(
|
|
|
324
377
|
})
|
|
325
378
|
: await client.createPrivateResource({
|
|
326
379
|
resourceType: resourceType(entry.type),
|
|
380
|
+
strategyKind,
|
|
327
381
|
title: entry.title,
|
|
328
382
|
description: entry.description,
|
|
329
383
|
sourceFiles: uploadedSource,
|
|
330
384
|
packageFileId,
|
|
331
385
|
forkFromWorkspaceItemId: action === 'fork' ? entry.hub?.workspaceItemId : undefined,
|
|
332
386
|
});
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
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);
|
|
337
391
|
const updatedHubIdentity = {
|
|
338
392
|
resourceId: mutation.resourceId,
|
|
339
393
|
versionId: mutation.versionId,
|
|
340
|
-
|
|
394
|
+
workspaceItemId,
|
|
341
395
|
publisher: 'self',
|
|
342
396
|
baseSha256: payload.digest,
|
|
343
397
|
lastUploadedSha256: payload.digest,
|
|
@@ -356,14 +410,47 @@ export async function syncCapabilitiesToCloud(
|
|
|
356
410
|
version_id: mutation.versionId,
|
|
357
411
|
...(workspaceItemId ? { workspace_item_id: workspaceItemId } : {}),
|
|
358
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
|
+
}
|
|
359
442
|
if (action === 'fork' && entry.hub) {
|
|
360
443
|
try {
|
|
361
444
|
await client.installResource(entry.hub.resourceId);
|
|
362
445
|
updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
|
|
363
446
|
...updatedHubIdentity,
|
|
447
|
+
workspaceItemId,
|
|
364
448
|
pendingBackpackRestoreResourceId: undefined,
|
|
365
449
|
});
|
|
366
450
|
} catch (error) {
|
|
451
|
+
if (unavailableForkSource(error)) updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
|
|
452
|
+
...updatedHubIdentity, workspaceItemId, pendingBackpackRestoreResourceId: undefined,
|
|
453
|
+
});
|
|
367
454
|
result.failed.push({
|
|
368
455
|
type: entry.type,
|
|
369
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,9 +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;
|
|
32
34
|
/** The working copy existed before CCL had a trustworthy Hub baseline. */
|
|
33
35
|
localOriginUnrecognized?: boolean;
|
|
36
|
+
/** Cloud association is retained locally but automatic cloud I/O is suspended. */
|
|
37
|
+
cloudStatus?: 'workspace_missing';
|
|
34
38
|
}
|
|
35
39
|
|
|
36
40
|
export interface CapabilityWorkspaceEntry {
|
package/src/lib/game-client.ts
CHANGED
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
type GameSyncResumeState,
|
|
13
13
|
} from '../runtime/ws-client.js';
|
|
14
14
|
import { RuntimeLogger } from '../runtime/runtime-logger.js';
|
|
15
|
+
import { ThreadedWsClient, type ThreadedWsClientConfig } from '../runtime/threaded-ws-client.js';
|
|
15
16
|
import type { RawWsMessageSink } from '../runtime/raw-ws-log.js';
|
|
16
17
|
import type { GameSyncPerceptionReport } from '../runtime/game-sync-protocol.js';
|
|
17
18
|
import type { QueueMode } from './competition.js';
|
|
@@ -36,6 +37,8 @@ export interface GameClientConfig {
|
|
|
36
37
|
rawWsMessageSink?: RawWsMessageSink;
|
|
37
38
|
/** Cancels owner-scoped HTTP work before Action authority is released. */
|
|
38
39
|
signal?: AbortSignal;
|
|
40
|
+
/** Owner-only Source transport isolation. Ephemeral clients do not start an ingress Worker. */
|
|
41
|
+
gameSyncIngress?: Omit<ThreadedWsClientConfig, 'url' | 'apiKey' | 'resumeState'>;
|
|
39
42
|
}
|
|
40
43
|
|
|
41
44
|
export interface GameServerDiscoveryResult {
|
|
@@ -69,7 +72,10 @@ function agentMetadataHeaders(options: RoomEntryMetadata): Record<string, string
|
|
|
69
72
|
|
|
70
73
|
export class GameClient {
|
|
71
74
|
private http: HttpTransport;
|
|
72
|
-
private ws: WsClient | null = null;
|
|
75
|
+
private ws: Pick<WsClient, keyof WsClient> | null = null;
|
|
76
|
+
private readonly gameSyncIngress?: GameClientConfig['gameSyncIngress'];
|
|
77
|
+
private readonly closingIngress = new Set<Promise<void>>();
|
|
78
|
+
private transportGeneration = 0;
|
|
73
79
|
/** Last continuously reduced v2 baseline, retained across failed socket replacements. */
|
|
74
80
|
private gameSyncResumeState?: GameSyncResumeState;
|
|
75
81
|
/** Queue/room-owned game identity that the retained baseline must belong to. */
|
|
@@ -111,6 +117,7 @@ export class GameClient {
|
|
|
111
117
|
this.apiKey = config.apiKey;
|
|
112
118
|
this.enableWs = config.enableWs ?? false;
|
|
113
119
|
this.rawWsMessageSink = config.rawWsMessageSink;
|
|
120
|
+
this.gameSyncIngress = config.gameSyncIngress;
|
|
114
121
|
this.registry = new ServerRegistry({
|
|
115
122
|
lobbyUrl: config.lobbyUrl,
|
|
116
123
|
gameServerUrl: config.gameServerUrl,
|
|
@@ -196,8 +203,8 @@ export class GameClient {
|
|
|
196
203
|
}
|
|
197
204
|
|
|
198
205
|
/** Irreversible confirmed Action endpoint; input must already be prepared. */
|
|
199
|
-
async submitPreparedActionConfirmed(action: GameActionRequest): Promise<TransportResponse> {
|
|
200
|
-
return this.http.postRaw('/api/v1/game/action', action);
|
|
206
|
+
async submitPreparedActionConfirmed(action: GameActionRequest, signal?: AbortSignal): Promise<TransportResponse> {
|
|
207
|
+
return this.http.postRaw('/api/v1/game/action', action, undefined, signal);
|
|
201
208
|
}
|
|
202
209
|
|
|
203
210
|
private async prepareAction(action: GameActionRequest): Promise<GameActionRequest> {
|
|
@@ -469,11 +476,11 @@ export class GameClient {
|
|
|
469
476
|
if (resumeState) this.gameSyncResumeState = resumeState;
|
|
470
477
|
if (this.ws) {
|
|
471
478
|
this.ws.clearHandlers();
|
|
472
|
-
this.ws
|
|
479
|
+
await this.stopWs(this.ws);
|
|
473
480
|
this.markWsHandlersDetached();
|
|
474
481
|
}
|
|
475
482
|
|
|
476
|
-
const newWs =
|
|
483
|
+
const newWs = this.createWs({
|
|
477
484
|
url: wsUrl,
|
|
478
485
|
apiKey: this.apiKey,
|
|
479
486
|
rawMessageSink: this.rawWsMessageSink,
|
|
@@ -487,7 +494,7 @@ export class GameClient {
|
|
|
487
494
|
} catch {
|
|
488
495
|
this.rememberGameSyncResumeState(newWs.resumeState);
|
|
489
496
|
this.log.warn('WS_CONNECT', 'GameSync WebSocket connection failed; runtime will retry');
|
|
490
|
-
|
|
497
|
+
await this.stopWs(newWs);
|
|
491
498
|
this.ws = null;
|
|
492
499
|
this.markWsHandlersDetached();
|
|
493
500
|
return false;
|
|
@@ -500,7 +507,7 @@ export class GameClient {
|
|
|
500
507
|
this.rememberGameSyncResumeState(this.ws?.resumeState);
|
|
501
508
|
}
|
|
502
509
|
if (this.ws) {
|
|
503
|
-
this.ws
|
|
510
|
+
this.stopWs(this.ws);
|
|
504
511
|
this.ws = null;
|
|
505
512
|
}
|
|
506
513
|
if (!options.preserveGameSyncResumeState) {
|
|
@@ -559,11 +566,11 @@ export class GameClient {
|
|
|
559
566
|
if (resumeState) this.gameSyncResumeState = resumeState;
|
|
560
567
|
if (this.ws) {
|
|
561
568
|
this.ws.clearHandlers();
|
|
562
|
-
this.ws
|
|
569
|
+
await this.stopWs(this.ws);
|
|
563
570
|
this.markWsHandlersDetached();
|
|
564
571
|
}
|
|
565
572
|
|
|
566
|
-
const newWs =
|
|
573
|
+
const newWs = this.createWs({
|
|
567
574
|
url: wsUrl,
|
|
568
575
|
apiKey: this.apiKey,
|
|
569
576
|
rawMessageSink: this.rawWsMessageSink,
|
|
@@ -577,7 +584,7 @@ export class GameClient {
|
|
|
577
584
|
} catch {
|
|
578
585
|
this.rememberGameSyncResumeState(newWs.resumeState);
|
|
579
586
|
this.log.warn('WS_RECONNECT', 'GameSync WebSocket reconnect failed; runtime will retry');
|
|
580
|
-
|
|
587
|
+
await this.stopWs(newWs);
|
|
581
588
|
this.ws = null;
|
|
582
589
|
this.markWsHandlersDetached();
|
|
583
590
|
}
|
|
@@ -700,6 +707,29 @@ export class GameClient {
|
|
|
700
707
|
for (const entry of this.wsRecoveryStartedHandlers) entry.unsubscribe = undefined;
|
|
701
708
|
}
|
|
702
709
|
|
|
710
|
+
private createWs(config: ConstructorParameters<typeof WsClient>[0]): Pick<WsClient, keyof WsClient> {
|
|
711
|
+
if (!this.gameSyncIngress) return new WsClient(config);
|
|
712
|
+
const { rawMessageSink: _sink, ...options } = config;
|
|
713
|
+
return new ThreadedWsClient({ ...options, ...this.gameSyncIngress, transportGeneration: ++this.transportGeneration });
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
private stopWs(ws: Pick<WsClient, keyof WsClient>): Promise<void> {
|
|
717
|
+
ws.disconnect();
|
|
718
|
+
if (ws instanceof ThreadedWsClient) {
|
|
719
|
+
const closing = ws.close();
|
|
720
|
+
this.closingIngress.add(closing);
|
|
721
|
+
void closing.finally(() => this.closingIngress.delete(closing));
|
|
722
|
+
return closing;
|
|
723
|
+
}
|
|
724
|
+
return Promise.resolve();
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/** Drain Source-owned ingress and raw journals before Owner telemetry closes. */
|
|
728
|
+
async closeGameSyncTransports(): Promise<void> {
|
|
729
|
+
this.disconnectWs();
|
|
730
|
+
await Promise.allSettled([...this.closingIngress]);
|
|
731
|
+
}
|
|
732
|
+
|
|
703
733
|
private rememberGameSyncResumeState(candidate: GameSyncResumeState | undefined): void {
|
|
704
734
|
if (!candidate) return;
|
|
705
735
|
const expected = this.expectedGameSyncGameId;
|
|
@@ -135,8 +135,8 @@ export class HttpTransport {
|
|
|
135
135
|
}
|
|
136
136
|
}
|
|
137
137
|
|
|
138
|
-
async postRaw(path: string, body?: any, perRequestHeaders?: Record<string, string
|
|
139
|
-
return this.requestRaw('POST', path, body, perRequestHeaders);
|
|
138
|
+
async postRaw(path: string, body?: any, perRequestHeaders?: Record<string, string>, requestSignal?: AbortSignal): Promise<TransportResponse> {
|
|
139
|
+
return this.requestRaw('POST', path, body, perRequestHeaders, requestSignal);
|
|
140
140
|
}
|
|
141
141
|
|
|
142
142
|
/** GET with one fast retry for transient network failures. */
|