@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.
- package/docs/configuration.md +11 -12
- package/docs/custom-modules/README.md +3 -3
- package/docs/custom-modules/behavior.md +1 -1
- package/docs/custom-modules/perception.md +1 -1
- package/docs/custom-modules/trigger.md +1 -1
- package/docs/runtime/official-perception-modules.md +1 -1
- package/package.json +1 -1
- package/scripts/check-skill-command-surface.mjs +1 -0
- package/scripts/sync-bundled-skill.mjs +89 -52
- package/skills/clawclaw/SKILL.md +10 -6
- package/skills/clawclaw/references/BEHAVIORS.md +2 -0
- package/skills/clawclaw/references/CHANNELS.md +1 -1
- package/skills/clawclaw/references/COMMANDS.md +11 -4
- package/skills/clawclaw/references/HUB.md +4 -2
- package/skills/clawclaw/references/STREAM.md +4 -2
- package/src/cli.ts +2 -0
- package/src/commands/behavior.ts +49 -8
- package/src/commands/capability.ts +345 -0
- package/src/commands/load.ts +195 -8
- package/src/commands/perception.ts +21 -7
- package/src/commands/persona.ts +6 -0
- package/src/commands/trigger.ts +8 -5
- package/src/lib/agent-workspace-skills.ts +167 -68
- package/src/lib/agent-workspace-sync.ts +20 -31
- package/src/lib/capability-cloud-refresh.ts +313 -0
- package/src/lib/capability-cloud-sync.ts +315 -0
- package/src/lib/capability-discovery.ts +94 -0
- package/src/lib/capability-workspace.ts +291 -0
- package/src/lib/game-client.ts +12 -4
- package/src/lib/hub-client.ts +131 -4
- package/src/lib/persona.ts +1 -24
- package/src/lib/skill-host.ts +63 -0
- package/src/lib/user-data.ts +47 -59
- package/src/lib/zip-store.ts +92 -0
- package/src/pipeline/event-format.ts +5 -0
- package/src/pipeline/event-hints.ts +10 -0
- package/src/runtime/clawclaw/agent-event-policy.ts +2 -0
- package/src/runtime/clawclaw/behavior-input.ts +5 -0
- package/src/runtime/clawclaw/owner.ts +12 -12
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +150 -18
- package/src/runtime/clawclaw/plugins/behavior/behavior-action.ts +8 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-decision-history.ts +88 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +173 -11
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +6 -0
- package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +3 -1
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +5 -1
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +5 -5
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +213 -6
- package/src/runtime/clawclaw/plugins/source/game-transport.ts +29 -4
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +153 -0
- package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
- package/src/runtime/clawclaw/runtime.ts +31 -3
- package/src/runtime/clawclaw-event-catalog.ts +2 -0
- package/src/runtime/framework/events/event-repository.ts +1 -1
- package/src/runtime/framework/events/memory-event-repository.ts +59 -1
- package/src/runtime/framework/events/sqlite-event-repository.ts +23 -1
- package/src/runtime/framework/mailbox/types.ts +2 -0
- package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +58 -0
- package/src/runtime/framework/persistence/memory-first-persistence.ts +380 -0
- package/src/runtime/framework/plugins/contracts.ts +2 -2
- package/src/runtime/framework/plugins/runtime-input-journal.ts +173 -17
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +23 -11
- package/src/runtime/framework/runtime.ts +57 -4
- package/src/runtime/framework/state/history/contracts.ts +9 -1
- package/src/runtime/framework/state/history/memory-state-history-repository.ts +49 -7
- package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +16 -0
- package/src/sdk/behavior-plugin/index.ts +5 -24
- package/src/sdk/module-input/index.ts +47 -0
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import type { AuthProfile } from './auth.js';
|
|
4
|
+
import {
|
|
5
|
+
classifyStrategyLifecycle,
|
|
6
|
+
registerDiscoveredCapability,
|
|
7
|
+
type CapabilityWorkspaceEntry,
|
|
8
|
+
} from './capability-workspace.js';
|
|
9
|
+
import { listPersonaPresets } from './persona.js';
|
|
10
|
+
import { readSkillName } from './skill-host.js';
|
|
11
|
+
import {
|
|
12
|
+
ensureAccountUserDataLayout,
|
|
13
|
+
getUserDataAccountBehaviorsDir,
|
|
14
|
+
getUserDataAccountPerceptionsDir,
|
|
15
|
+
getUserDataAccountPersonasDir,
|
|
16
|
+
getUserDataAccountSkillsDir,
|
|
17
|
+
} from './user-data.js';
|
|
18
|
+
import {
|
|
19
|
+
listClawclawBehaviorSources,
|
|
20
|
+
type ResolvedClawclawBehaviorSource,
|
|
21
|
+
} from '../runtime/clawclaw/plugins/behavior/behavior-source.js';
|
|
22
|
+
import {
|
|
23
|
+
listClawclawPerceptionSourcesInDirectory,
|
|
24
|
+
type ResolvedClawclawPerceptionSource,
|
|
25
|
+
} from '../runtime/clawclaw/plugins/perception/perception-source.js';
|
|
26
|
+
|
|
27
|
+
export interface DiscoveredLocalCapabilities {
|
|
28
|
+
behaviors: Array<{ source: ResolvedClawclawBehaviorSource; entry: CapabilityWorkspaceEntry }>;
|
|
29
|
+
perceptions: Array<{ source: ResolvedClawclawPerceptionSource; entry: CapabilityWorkspaceEntry }>;
|
|
30
|
+
personas: CapabilityWorkspaceEntry[];
|
|
31
|
+
skills: CapabilityWorkspaceEntry[];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function discoverLocalCapabilities(
|
|
35
|
+
workspaceDir: string,
|
|
36
|
+
profile: Pick<AuthProfile, 'apiKey'>,
|
|
37
|
+
): DiscoveredLocalCapabilities {
|
|
38
|
+
ensureAccountUserDataLayout(workspaceDir, profile);
|
|
39
|
+
const behaviors = listClawclawBehaviorSources(
|
|
40
|
+
getUserDataAccountBehaviorsDir(workspaceDir, profile),
|
|
41
|
+
).map((source) => ({
|
|
42
|
+
source,
|
|
43
|
+
entry: registerDiscoveredCapability(workspaceDir, profile, {
|
|
44
|
+
type: 'behavior',
|
|
45
|
+
path: source.sourcePath,
|
|
46
|
+
runtimeId: source.id,
|
|
47
|
+
title: source.name,
|
|
48
|
+
description: source.description,
|
|
49
|
+
strategyLifecycle: classifyStrategyLifecycle(readFileSync(source.sourcePath, 'utf8')),
|
|
50
|
+
}),
|
|
51
|
+
}));
|
|
52
|
+
const perceptions = listClawclawPerceptionSourcesInDirectory(
|
|
53
|
+
getUserDataAccountPerceptionsDir(workspaceDir, profile),
|
|
54
|
+
).map((source) => ({
|
|
55
|
+
source,
|
|
56
|
+
entry: registerDiscoveredCapability(workspaceDir, profile, {
|
|
57
|
+
type: 'perception',
|
|
58
|
+
path: source.sourcePath,
|
|
59
|
+
runtimeId: source.id,
|
|
60
|
+
title: source.name,
|
|
61
|
+
description: source.description,
|
|
62
|
+
}),
|
|
63
|
+
}));
|
|
64
|
+
const personas = listPersonaPresets(
|
|
65
|
+
getUserDataAccountPersonasDir(workspaceDir, profile),
|
|
66
|
+
).map((preset) => registerDiscoveredCapability(workspaceDir, profile, {
|
|
67
|
+
type: 'persona',
|
|
68
|
+
path: preset.path,
|
|
69
|
+
runtimeId: preset.id,
|
|
70
|
+
title: preset.name,
|
|
71
|
+
description: `Persona ${preset.name}`,
|
|
72
|
+
}));
|
|
73
|
+
const skillsRoot = getUserDataAccountSkillsDir(workspaceDir, profile);
|
|
74
|
+
const skills = existsSync(skillsRoot)
|
|
75
|
+
? readdirSync(skillsRoot, { withFileTypes: true }).flatMap((item) => {
|
|
76
|
+
if (!item.isDirectory()) return [];
|
|
77
|
+
const path = join(skillsRoot, item.name);
|
|
78
|
+
try {
|
|
79
|
+
if (!statSync(path).isDirectory()) return [];
|
|
80
|
+
} catch {
|
|
81
|
+
return [];
|
|
82
|
+
}
|
|
83
|
+
const name = readSkillName(path);
|
|
84
|
+
return name ? [registerDiscoveredCapability(workspaceDir, profile, {
|
|
85
|
+
type: 'skill',
|
|
86
|
+
path,
|
|
87
|
+
runtimeId: name,
|
|
88
|
+
title: name,
|
|
89
|
+
description: `Skill ${name}`,
|
|
90
|
+
})] : [];
|
|
91
|
+
})
|
|
92
|
+
: [];
|
|
93
|
+
return { behaviors, perceptions, personas, skills };
|
|
94
|
+
}
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import {
|
|
2
|
+
cpSync,
|
|
3
|
+
existsSync,
|
|
4
|
+
mkdirSync,
|
|
5
|
+
readFileSync,
|
|
6
|
+
renameSync,
|
|
7
|
+
writeFileSync,
|
|
8
|
+
} from 'node:fs';
|
|
9
|
+
import { randomUUID } from 'node:crypto';
|
|
10
|
+
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
11
|
+
import type { AuthProfile } from './auth.js';
|
|
12
|
+
import {
|
|
13
|
+
getUserDataAccountCapabilitiesDir,
|
|
14
|
+
getUserDataAccountCapabilityRegistryFile,
|
|
15
|
+
getUserDataAccountDraftsDir,
|
|
16
|
+
getUserDataAccountDir,
|
|
17
|
+
} from './user-data.js';
|
|
18
|
+
|
|
19
|
+
export type CapabilityWorkspaceType = 'behavior' | 'perception' | 'persona' | 'skill';
|
|
20
|
+
export type CapabilitySelection = 'pending' | 'equipped' | 'unequipped';
|
|
21
|
+
export type StrategyLifecycle = 'long' | 'short';
|
|
22
|
+
|
|
23
|
+
export interface CapabilityHubIdentity {
|
|
24
|
+
resourceId: string;
|
|
25
|
+
versionId: string;
|
|
26
|
+
workspaceItemId?: string;
|
|
27
|
+
publisher: 'official' | 'self' | 'community';
|
|
28
|
+
baseSha256?: string;
|
|
29
|
+
lastUploadedSha256?: string;
|
|
30
|
+
pendingBackpackRestoreResourceId?: string;
|
|
31
|
+
observedCloudVersionId?: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface CapabilityWorkspaceEntry {
|
|
35
|
+
key: string;
|
|
36
|
+
type: CapabilityWorkspaceType;
|
|
37
|
+
origin: 'local' | 'hub';
|
|
38
|
+
relativePath: string;
|
|
39
|
+
runtimeId: string;
|
|
40
|
+
title: string;
|
|
41
|
+
description: string;
|
|
42
|
+
selection: CapabilitySelection;
|
|
43
|
+
strategyLifecycle?: StrategyLifecycle;
|
|
44
|
+
conflictChoice?: 'local';
|
|
45
|
+
hub?: CapabilityHubIdentity;
|
|
46
|
+
discoveredAt: string;
|
|
47
|
+
updatedAt: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface CapabilityWorkspaceRegistry {
|
|
51
|
+
format: 1;
|
|
52
|
+
entries: Record<string, CapabilityWorkspaceEntry>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const EMPTY = (): CapabilityWorkspaceRegistry => ({ format: 1, entries: {} });
|
|
56
|
+
const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/;
|
|
57
|
+
|
|
58
|
+
function pathInside(root: string, candidate: string): boolean {
|
|
59
|
+
const child = relative(resolve(root), resolve(candidate));
|
|
60
|
+
return child === '' || (!child.startsWith('..') && !isAbsolute(child));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function normalizedRelativePath(root: string, path: string): string {
|
|
64
|
+
const absolute = resolve(path);
|
|
65
|
+
if (!pathInside(root, absolute)) throw new Error('capability_workspace_path_escape');
|
|
66
|
+
const value = relative(resolve(root), absolute).replaceAll('\\', '/');
|
|
67
|
+
if (!value || value.split('/').some((segment) => !segment || segment === '.' || segment === '..')) {
|
|
68
|
+
throw new Error('capability_workspace_relative_path_invalid');
|
|
69
|
+
}
|
|
70
|
+
return value;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function registryKey(type: CapabilityWorkspaceType, relativePath: string): string {
|
|
74
|
+
return `${type}:${relativePath}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function writeRegistryFile(path: string, registry: CapabilityWorkspaceRegistry): void {
|
|
78
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
79
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
80
|
+
writeFileSync(temporary, `${JSON.stringify(registry, null, 2)}\n`, 'utf8');
|
|
81
|
+
renameSync(temporary, path);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function readCapabilityWorkspaceRegistry(
|
|
85
|
+
workspaceDir: string,
|
|
86
|
+
profile: Pick<AuthProfile, 'apiKey'>,
|
|
87
|
+
): CapabilityWorkspaceRegistry {
|
|
88
|
+
const path = getUserDataAccountCapabilityRegistryFile(workspaceDir, profile);
|
|
89
|
+
if (!existsSync(path)) return EMPTY();
|
|
90
|
+
try {
|
|
91
|
+
const value = JSON.parse(readFileSync(path, 'utf8')) as CapabilityWorkspaceRegistry;
|
|
92
|
+
if (value.format !== 1 || !value.entries || typeof value.entries !== 'object') return EMPTY();
|
|
93
|
+
return value;
|
|
94
|
+
} catch {
|
|
95
|
+
return EMPTY();
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function writeCapabilityWorkspaceRegistry(
|
|
100
|
+
workspaceDir: string,
|
|
101
|
+
profile: Pick<AuthProfile, 'apiKey'>,
|
|
102
|
+
registry: CapabilityWorkspaceRegistry,
|
|
103
|
+
): void {
|
|
104
|
+
writeRegistryFile(getUserDataAccountCapabilityRegistryFile(workspaceDir, profile), registry);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function registerDiscoveredCapability(
|
|
108
|
+
workspaceDir: string,
|
|
109
|
+
profile: Pick<AuthProfile, 'apiKey'>,
|
|
110
|
+
input: {
|
|
111
|
+
type: CapabilityWorkspaceType;
|
|
112
|
+
path: string;
|
|
113
|
+
runtimeId: string;
|
|
114
|
+
title?: string;
|
|
115
|
+
description?: string;
|
|
116
|
+
strategyLifecycle?: StrategyLifecycle;
|
|
117
|
+
hub?: CapabilityHubIdentity;
|
|
118
|
+
selectedByHub?: boolean;
|
|
119
|
+
},
|
|
120
|
+
): CapabilityWorkspaceEntry {
|
|
121
|
+
const validRuntimeId = input.type === 'persona'
|
|
122
|
+
? !!input.runtimeId.trim()
|
|
123
|
+
&& input.runtimeId.length <= 255
|
|
124
|
+
&& !/[\\/\u0000-\u001f]/u.test(input.runtimeId)
|
|
125
|
+
: SAFE_ID.test(input.runtimeId);
|
|
126
|
+
if (!validRuntimeId) throw new Error('capability_workspace_runtime_id_invalid');
|
|
127
|
+
const root = getUserDataAccountCapabilitiesDir(workspaceDir, profile);
|
|
128
|
+
const relativePath = normalizedRelativePath(root, input.path);
|
|
129
|
+
const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
|
|
130
|
+
const existingByResource = input.hub
|
|
131
|
+
? Object.values(registry.entries).find((entry) => (
|
|
132
|
+
entry.type === input.type && entry.hub?.resourceId === input.hub?.resourceId
|
|
133
|
+
))
|
|
134
|
+
: undefined;
|
|
135
|
+
const key = existingByResource?.key ?? registryKey(input.type, relativePath);
|
|
136
|
+
const now = new Date().toISOString();
|
|
137
|
+
const previous = registry.entries[key];
|
|
138
|
+
const entry: CapabilityWorkspaceEntry = {
|
|
139
|
+
key,
|
|
140
|
+
type: input.type,
|
|
141
|
+
origin: previous?.origin ?? (input.selectedByHub ? 'hub' : 'local'),
|
|
142
|
+
relativePath,
|
|
143
|
+
runtimeId: input.runtimeId,
|
|
144
|
+
title: input.title?.trim() || previous?.title || input.runtimeId,
|
|
145
|
+
description: input.description?.trim() || previous?.description || `${input.type} ${input.runtimeId}`,
|
|
146
|
+
selection: input.selectedByHub
|
|
147
|
+
? 'equipped'
|
|
148
|
+
: previous?.selection ?? 'pending',
|
|
149
|
+
...(input.strategyLifecycle ? { strategyLifecycle: input.strategyLifecycle } : {}),
|
|
150
|
+
...(previous?.conflictChoice ? { conflictChoice: previous.conflictChoice } : {}),
|
|
151
|
+
...(input.hub ? { hub: { ...previous?.hub, ...input.hub } } : previous?.hub ? { hub: previous.hub } : {}),
|
|
152
|
+
discoveredAt: previous?.discoveredAt ?? now,
|
|
153
|
+
updatedAt: now,
|
|
154
|
+
};
|
|
155
|
+
if (previous && previous.relativePath !== relativePath) delete registry.entries[previous.key];
|
|
156
|
+
registry.entries[key] = entry;
|
|
157
|
+
writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
|
|
158
|
+
return entry;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function capabilityEntryForPath(
|
|
162
|
+
workspaceDir: string,
|
|
163
|
+
profile: Pick<AuthProfile, 'apiKey'>,
|
|
164
|
+
type: CapabilityWorkspaceType,
|
|
165
|
+
path: string,
|
|
166
|
+
): CapabilityWorkspaceEntry | undefined {
|
|
167
|
+
const root = getUserDataAccountCapabilitiesDir(workspaceDir, profile);
|
|
168
|
+
const relativePath = normalizedRelativePath(root, path);
|
|
169
|
+
const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
|
|
170
|
+
return registry.entries[registryKey(type, relativePath)]
|
|
171
|
+
?? Object.values(registry.entries).find((entry) => (
|
|
172
|
+
entry.type === type && entry.relativePath === relativePath
|
|
173
|
+
));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function capabilityEntryForHubResource(
|
|
177
|
+
workspaceDir: string,
|
|
178
|
+
profile: Pick<AuthProfile, 'apiKey'>,
|
|
179
|
+
type: CapabilityWorkspaceType,
|
|
180
|
+
resourceId: string,
|
|
181
|
+
): CapabilityWorkspaceEntry | undefined {
|
|
182
|
+
return Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
|
|
183
|
+
.find((entry) => entry.type === type && entry.hub?.resourceId === resourceId);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function setCapabilitySelection(
|
|
187
|
+
workspaceDir: string,
|
|
188
|
+
profile: Pick<AuthProfile, 'apiKey'>,
|
|
189
|
+
type: CapabilityWorkspaceType,
|
|
190
|
+
runtimeId: string,
|
|
191
|
+
equipped: boolean,
|
|
192
|
+
): CapabilityWorkspaceEntry {
|
|
193
|
+
const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
|
|
194
|
+
const matches = Object.values(registry.entries)
|
|
195
|
+
.filter((entry) => entry.type === type && entry.runtimeId === runtimeId && entry.origin === 'local');
|
|
196
|
+
if (matches.length !== 1) throw new Error(`capability_selection_${matches.length === 0 ? 'not_found' : 'ambiguous'}:${type}:${runtimeId}`);
|
|
197
|
+
const entry = matches[0]!;
|
|
198
|
+
entry.selection = equipped ? 'equipped' : 'unequipped';
|
|
199
|
+
entry.updatedAt = new Date().toISOString();
|
|
200
|
+
writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
|
|
201
|
+
return entry;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function updateCapabilityHubIdentity(
|
|
205
|
+
workspaceDir: string,
|
|
206
|
+
profile: Pick<AuthProfile, 'apiKey'>,
|
|
207
|
+
key: string,
|
|
208
|
+
hub: CapabilityHubIdentity,
|
|
209
|
+
): CapabilityWorkspaceEntry {
|
|
210
|
+
const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
|
|
211
|
+
const entry = registry.entries[key];
|
|
212
|
+
if (!entry) throw new Error(`capability_workspace_entry_missing:${key}`);
|
|
213
|
+
entry.hub = { ...entry.hub, ...hub };
|
|
214
|
+
entry.updatedAt = new Date().toISOString();
|
|
215
|
+
writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
|
|
216
|
+
return entry;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export function setCapabilityConflictChoice(
|
|
220
|
+
workspaceDir: string,
|
|
221
|
+
profile: Pick<AuthProfile, 'apiKey'>,
|
|
222
|
+
key: string,
|
|
223
|
+
choice: 'local' | undefined,
|
|
224
|
+
): CapabilityWorkspaceEntry {
|
|
225
|
+
const registry = readCapabilityWorkspaceRegistry(workspaceDir, profile);
|
|
226
|
+
const entry = registry.entries[key];
|
|
227
|
+
if (!entry) throw new Error(`capability_workspace_entry_missing:${key}`);
|
|
228
|
+
if (choice) entry.conflictChoice = choice;
|
|
229
|
+
else delete entry.conflictChoice;
|
|
230
|
+
entry.updatedAt = new Date().toISOString();
|
|
231
|
+
writeCapabilityWorkspaceRegistry(workspaceDir, profile, registry);
|
|
232
|
+
return entry;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export function pendingCapabilitySelections(
|
|
236
|
+
workspaceDir: string,
|
|
237
|
+
profile: Pick<AuthProfile, 'apiKey'>,
|
|
238
|
+
): readonly CapabilityWorkspaceEntry[] {
|
|
239
|
+
return Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
|
|
240
|
+
.filter((entry) => entry.origin === 'local' && entry.selection === 'pending')
|
|
241
|
+
.sort((left, right) => left.discoveredAt.localeCompare(right.discoveredAt));
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export function capabilityWorkspacePath(
|
|
245
|
+
workspaceDir: string,
|
|
246
|
+
profile: Pick<AuthProfile, 'apiKey'>,
|
|
247
|
+
entry: Pick<CapabilityWorkspaceEntry, 'relativePath'>,
|
|
248
|
+
): string {
|
|
249
|
+
const root = getUserDataAccountCapabilitiesDir(workspaceDir, profile);
|
|
250
|
+
const path = resolve(root, ...entry.relativePath.split('/'));
|
|
251
|
+
if (!pathInside(root, path)) throw new Error('capability_workspace_path_escape');
|
|
252
|
+
return path;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export function saveCapabilityDraft(
|
|
256
|
+
workspaceDir: string,
|
|
257
|
+
profile: Pick<AuthProfile, 'apiKey'>,
|
|
258
|
+
input: { type: CapabilityWorkspaceType; runtimeId: string; bytes: Buffer; extension: string },
|
|
259
|
+
): string {
|
|
260
|
+
const safeRuntimeId = SAFE_ID.test(input.runtimeId) ? input.runtimeId : 'capability';
|
|
261
|
+
const directory = join(
|
|
262
|
+
getUserDataAccountDraftsDir(workspaceDir, profile),
|
|
263
|
+
input.type,
|
|
264
|
+
`${safeRuntimeId}-${randomUUID()}`,
|
|
265
|
+
);
|
|
266
|
+
mkdirSync(directory, { recursive: true });
|
|
267
|
+
const path = join(directory, `${safeRuntimeId}${input.extension}`);
|
|
268
|
+
writeFileSync(path, input.bytes);
|
|
269
|
+
return path;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export function saveCapabilityDirectoryDraft(
|
|
273
|
+
workspaceDir: string,
|
|
274
|
+
profile: Pick<AuthProfile, 'apiKey'>,
|
|
275
|
+
input: { type: CapabilityWorkspaceType; runtimeId: string; sourcePath: string },
|
|
276
|
+
): string {
|
|
277
|
+
const safeRuntimeId = SAFE_ID.test(input.runtimeId) ? input.runtimeId : 'capability';
|
|
278
|
+
const directory = join(
|
|
279
|
+
getUserDataAccountDraftsDir(workspaceDir, profile),
|
|
280
|
+
input.type,
|
|
281
|
+
`${safeRuntimeId}-${randomUUID()}`,
|
|
282
|
+
);
|
|
283
|
+
mkdirSync(dirname(directory), { recursive: true });
|
|
284
|
+
cpSync(input.sourcePath, directory, { recursive: true, errorOnExist: true });
|
|
285
|
+
return directory;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Product classification: a Behavior that can emit a finish effect is short. */
|
|
289
|
+
export function classifyStrategyLifecycle(source: string): StrategyLifecycle {
|
|
290
|
+
return /\bfinish\s*:|\bfinished\s*\(/.test(source) ? 'short' : 'long';
|
|
291
|
+
}
|
package/src/lib/game-client.ts
CHANGED
|
@@ -37,6 +37,13 @@ export interface GameClientConfig {
|
|
|
37
37
|
signal?: AbortSignal;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
export interface GameServerDiscoveryResult {
|
|
41
|
+
/** Preserves the old boolean meaning: a usable GameServer route changed. */
|
|
42
|
+
readonly routeChanged: boolean;
|
|
43
|
+
/** Latest authoritative Lobby participation response, when the probe succeeded. */
|
|
44
|
+
readonly queue?: Record<string, any>;
|
|
45
|
+
}
|
|
46
|
+
|
|
40
47
|
export interface GameActionRequest {
|
|
41
48
|
action: string;
|
|
42
49
|
name?: string;
|
|
@@ -510,12 +517,12 @@ export class GameClient {
|
|
|
510
517
|
/**
|
|
511
518
|
* Try to discover game server from /queue/status.
|
|
512
519
|
* If found and WS is enabled, reconnects WS to the game server.
|
|
513
|
-
* Returns
|
|
520
|
+
* Returns both the usable-route decision and the authoritative queue probe.
|
|
514
521
|
*
|
|
515
522
|
* Note: uses http.get directly instead of getQueueStatus() to avoid
|
|
516
523
|
* double-calling registry.updateFromQueueResponse().
|
|
517
524
|
*/
|
|
518
|
-
async discoverGameServer(): Promise<
|
|
525
|
+
async discoverGameServer(): Promise<GameServerDiscoveryResult> {
|
|
519
526
|
try {
|
|
520
527
|
const result = await this.http.get<any>('/api/v1/queue/status');
|
|
521
528
|
const changed = this.registry.updateFromQueueResponse(result);
|
|
@@ -524,10 +531,11 @@ export class GameClient {
|
|
|
524
531
|
if (this.enableWs) {
|
|
525
532
|
await this.reconnectWsToGameServer();
|
|
526
533
|
}
|
|
527
|
-
return true;
|
|
534
|
+
return { routeChanged: true, queue: structuredClone(result) };
|
|
528
535
|
}
|
|
536
|
+
return { routeChanged: false, queue: structuredClone(result) };
|
|
529
537
|
} catch { /* queue/status unavailable */ }
|
|
530
|
-
return false;
|
|
538
|
+
return { routeChanged: false };
|
|
531
539
|
}
|
|
532
540
|
|
|
533
541
|
/** Reconnect WS to the current game server address. */
|
package/src/lib/hub-client.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { AuthStore } from './auth.js';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
2
3
|
import { ServerRegistry } from './server-registry.js';
|
|
3
4
|
import { HttpTransport } from './http-transport.js';
|
|
4
5
|
|
|
@@ -131,6 +132,23 @@ interface RawWorkspaceItem {
|
|
|
131
132
|
has_update?: boolean;
|
|
132
133
|
}
|
|
133
134
|
|
|
135
|
+
export interface HubSourceFileUpload {
|
|
136
|
+
relativePath: string;
|
|
137
|
+
filename: string;
|
|
138
|
+
bytes: Buffer;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export interface HubUploadedSourceFile {
|
|
142
|
+
relative_path: string;
|
|
143
|
+
file_id: string;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export interface HubResourceMutationResult {
|
|
147
|
+
resourceId: string;
|
|
148
|
+
versionId: string;
|
|
149
|
+
workspaceItemId?: string;
|
|
150
|
+
}
|
|
151
|
+
|
|
134
152
|
function resourceVersion(resource: RawResource): RawVersion {
|
|
135
153
|
const version = resource.latest_version ?? resource.published_version ?? resource.version;
|
|
136
154
|
if (!version) throw new Error(`Hub resource '${resource.resource_id}' has no visible version`);
|
|
@@ -223,9 +241,11 @@ export class HubClient {
|
|
|
223
241
|
};
|
|
224
242
|
}
|
|
225
243
|
|
|
226
|
-
async getResource(type: ResourceType, id: string): Promise<ResourceDetail> {
|
|
244
|
+
async getResource(type: ResourceType, id: string, workspaceItemId?: string): Promise<ResourceDetail> {
|
|
245
|
+
const query = new URLSearchParams({ resource_id: id });
|
|
246
|
+
if (workspaceItemId) query.set('workspace_item_id', workspaceItemId);
|
|
227
247
|
const response = await this.http.get<Envelope<RawResource>>(
|
|
228
|
-
`${BASE}/resources/detail
|
|
248
|
+
`${BASE}/resources/detail?${query.toString()}`,
|
|
229
249
|
);
|
|
230
250
|
if (response.data.resource_type !== type) {
|
|
231
251
|
throw new Error(`Hub resource '${id}' is ${response.data.resource_type}, not ${type}`);
|
|
@@ -234,9 +254,11 @@ export class HubClient {
|
|
|
234
254
|
return { ...summary, artifact: { fileName: summary.fileName, downloadUrl: '' } };
|
|
235
255
|
}
|
|
236
256
|
|
|
237
|
-
async downloadArtifact(_type: ResourceType, id: string): Promise<Buffer> {
|
|
257
|
+
async downloadArtifact(_type: ResourceType, id: string, workspaceItemId?: string): Promise<Buffer> {
|
|
258
|
+
const query = new URLSearchParams({ resource_id: id });
|
|
259
|
+
if (workspaceItemId) query.set('workspace_item_id', workspaceItemId);
|
|
238
260
|
const response = await this.http.get<Envelope<{ url: string }>>(
|
|
239
|
-
`${BASE}/resources/file-download-url
|
|
261
|
+
`${BASE}/resources/file-download-url?${query.toString()}`,
|
|
240
262
|
);
|
|
241
263
|
return this.downloadUrl(response.data.url);
|
|
242
264
|
}
|
|
@@ -303,4 +325,109 @@ export class HubClient {
|
|
|
303
325
|
async deleteWorkspaceItem(workspaceItemId: string): Promise<void> {
|
|
304
326
|
await this.http.post(`${BASE}/workspace/delete`, { workspace_item_id: workspaceItemId });
|
|
305
327
|
}
|
|
328
|
+
|
|
329
|
+
async uploadFiles(
|
|
330
|
+
fileType: string,
|
|
331
|
+
files: readonly HubSourceFileUpload[],
|
|
332
|
+
): Promise<readonly HubUploadedSourceFile[]> {
|
|
333
|
+
if (files.length === 0) throw new Error('Hub upload requires at least one file.');
|
|
334
|
+
const declarations = files.map((file) => ({
|
|
335
|
+
filename: file.filename,
|
|
336
|
+
size_bytes: file.bytes.length,
|
|
337
|
+
sha256: createHash('sha256').update(file.bytes).digest('hex'),
|
|
338
|
+
}));
|
|
339
|
+
const prepared = await this.http.post<Envelope<{
|
|
340
|
+
items: Array<{
|
|
341
|
+
file_id: string;
|
|
342
|
+
upload_url: string;
|
|
343
|
+
file_field: string;
|
|
344
|
+
form_fields: Record<string, string>;
|
|
345
|
+
content_type: string;
|
|
346
|
+
}>;
|
|
347
|
+
}>>('/api/v1/files/prepare', { file_type: fileType, files: declarations });
|
|
348
|
+
if (prepared.data.items.length !== files.length) throw new Error('Hub upload preparation count mismatch.');
|
|
349
|
+
for (let index = 0; index < files.length; index += 1) {
|
|
350
|
+
const file = files[index]!;
|
|
351
|
+
const policy = prepared.data.items[index]!;
|
|
352
|
+
const form = new FormData();
|
|
353
|
+
for (const [name, value] of Object.entries(policy.form_fields)) form.append(name, value);
|
|
354
|
+
form.append(
|
|
355
|
+
policy.file_field,
|
|
356
|
+
new Blob([Uint8Array.from(file.bytes)], { type: policy.content_type }),
|
|
357
|
+
file.filename,
|
|
358
|
+
);
|
|
359
|
+
const response = await fetch(policy.upload_url, {
|
|
360
|
+
method: 'POST',
|
|
361
|
+
body: form,
|
|
362
|
+
signal: AbortSignal.timeout(30_000),
|
|
363
|
+
});
|
|
364
|
+
if (!response.ok) throw new Error(`Hub object upload failed (${response.status}).`);
|
|
365
|
+
}
|
|
366
|
+
const fileIds = prepared.data.items.map((item) => item.file_id);
|
|
367
|
+
const completed = await this.http.post<Envelope<{
|
|
368
|
+
items: Array<{ file_id: string; status: string }>;
|
|
369
|
+
}>>('/api/v1/files/complete', { file_ids: fileIds });
|
|
370
|
+
if (
|
|
371
|
+
completed.data.items.length !== fileIds.length
|
|
372
|
+
|| completed.data.items.some((item) => item.status !== 'ready')
|
|
373
|
+
) throw new Error('Hub upload completion failed.');
|
|
374
|
+
return files.map((file, index) => ({
|
|
375
|
+
relative_path: file.relativePath,
|
|
376
|
+
file_id: fileIds[index]!,
|
|
377
|
+
}));
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
async createPrivateResource(input: {
|
|
381
|
+
resourceType: ResourceType;
|
|
382
|
+
title: string;
|
|
383
|
+
description: string;
|
|
384
|
+
sourceFiles: readonly HubUploadedSourceFile[];
|
|
385
|
+
packageFileId?: string;
|
|
386
|
+
forkFromWorkspaceItemId?: string;
|
|
387
|
+
}): Promise<HubResourceMutationResult> {
|
|
388
|
+
const response = await this.http.post<Envelope<{
|
|
389
|
+
resource_id: string;
|
|
390
|
+
latest_version: { id: string };
|
|
391
|
+
workspace_item_id?: string;
|
|
392
|
+
}>>(`${BASE}/resources/create`, {
|
|
393
|
+
resource_type: input.resourceType,
|
|
394
|
+
title: input.title,
|
|
395
|
+
description: input.description,
|
|
396
|
+
icon_url: null,
|
|
397
|
+
source_files: input.sourceFiles,
|
|
398
|
+
package_file_id: input.packageFileId ?? null,
|
|
399
|
+
fork_from_workspace_item_id: input.forkFromWorkspaceItemId ?? null,
|
|
400
|
+
});
|
|
401
|
+
return {
|
|
402
|
+
resourceId: response.data.resource_id,
|
|
403
|
+
versionId: response.data.latest_version.id,
|
|
404
|
+
...(response.data.workspace_item_id ? { workspaceItemId: response.data.workspace_item_id } : {}),
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
async createPrivateVersion(input: {
|
|
409
|
+
resourceId: string;
|
|
410
|
+
baseVersionId: string;
|
|
411
|
+
title: string;
|
|
412
|
+
description: string;
|
|
413
|
+
sourceFiles: readonly HubUploadedSourceFile[];
|
|
414
|
+
packageFileId?: string;
|
|
415
|
+
}): Promise<HubResourceMutationResult> {
|
|
416
|
+
const response = await this.http.post<Envelope<{
|
|
417
|
+
resource_id: string;
|
|
418
|
+
latest_version: { id: string };
|
|
419
|
+
}>>(`${BASE}/resources/version/create`, {
|
|
420
|
+
resource_id: input.resourceId,
|
|
421
|
+
base_version_id: input.baseVersionId,
|
|
422
|
+
title: input.title,
|
|
423
|
+
description: input.description,
|
|
424
|
+
icon_url: null,
|
|
425
|
+
source_files: input.sourceFiles,
|
|
426
|
+
package_file_id: input.packageFileId ?? null,
|
|
427
|
+
});
|
|
428
|
+
return {
|
|
429
|
+
resourceId: response.data.resource_id,
|
|
430
|
+
versionId: response.data.latest_version.id,
|
|
431
|
+
};
|
|
432
|
+
}
|
|
306
433
|
}
|
package/src/lib/persona.ts
CHANGED
|
@@ -8,7 +8,6 @@ import {
|
|
|
8
8
|
getUserDataAccountPersonaSelectionFile,
|
|
9
9
|
getUserDataAccountHubPersonasDir,
|
|
10
10
|
getUserDataAccountPersonasDir,
|
|
11
|
-
getUserDataPersonaFile,
|
|
12
11
|
} from './user-data.js';
|
|
13
12
|
import {
|
|
14
13
|
readLocalAgentWorkspaceSnapshot,
|
|
@@ -144,28 +143,6 @@ function hubPersona(
|
|
|
144
143
|
return { path: working ?? null, source: 'hub', resourceId: item.resourceId };
|
|
145
144
|
}
|
|
146
145
|
|
|
147
|
-
function migrateLegacyPersonaWithoutHub(
|
|
148
|
-
workspaceDir: string,
|
|
149
|
-
profile: Pick<AuthProfile, 'apiKey'>,
|
|
150
|
-
): PersonaSelection | undefined {
|
|
151
|
-
const legacy = getUserDataPersonaFile(workspaceDir, profile);
|
|
152
|
-
if (!existsSync(legacy)) return undefined;
|
|
153
|
-
const content = readFileSync(legacy, 'utf8');
|
|
154
|
-
if (!content.trim()) return undefined;
|
|
155
|
-
const directory = getUserDataAccountPersonasDir(workspaceDir, profile);
|
|
156
|
-
mkdirSync(directory, { recursive: true });
|
|
157
|
-
let id = 'legacy';
|
|
158
|
-
let target = join(directory, `${id}.md`);
|
|
159
|
-
if (existsSync(target) && readFileSync(target, 'utf8') !== content) {
|
|
160
|
-
id = `legacy-${randomUUID().slice(0, 8)}`;
|
|
161
|
-
target = join(directory, `${id}.md`);
|
|
162
|
-
}
|
|
163
|
-
if (!existsSync(target)) writeFileSync(target, content, 'utf8');
|
|
164
|
-
const selection = { source: 'local', id } as const;
|
|
165
|
-
writePersonaSelection(workspaceDir, profile, selection);
|
|
166
|
-
return selection;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
146
|
export function resolveActivePersonaFile(authStore = new AuthStore()): ResolvedPersonaFile {
|
|
170
147
|
const profile = authStore.getActive();
|
|
171
148
|
if (!profile) throw new Error('Not logged in.');
|
|
@@ -174,7 +151,7 @@ export function resolveActivePersonaFile(authStore = new AuthStore()): ResolvedP
|
|
|
174
151
|
const snapshot = readLocalAgentWorkspaceSnapshot(workspaceDir, profile);
|
|
175
152
|
const selectedHub = hubPersona(workspaceDir, profile, snapshot);
|
|
176
153
|
const selection = readPersonaSelection(workspaceDir, profile)
|
|
177
|
-
?? (selectedHub ? { source: 'hub' as const } :
|
|
154
|
+
?? (selectedHub ? { source: 'hub' as const } : { source: 'none' as const });
|
|
178
155
|
if (selection?.source === 'local') {
|
|
179
156
|
const preset = findPersonaPreset(selection.id, getUserDataAccountPersonasDir(workspaceDir, profile));
|
|
180
157
|
return { path: preset?.path ?? null, source: 'local', id: selection.id };
|