@arcadia-eternity/content-sdk 4.12.0 → 4.14.0

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 (67) hide show
  1. package/README.md +16 -5
  2. package/dist/appimage-sdk.d.ts +2 -0
  3. package/dist/appimage-sdk.js +110 -0
  4. package/dist/author-api.d.ts +6 -1
  5. package/dist/author-api.js +27 -3
  6. package/dist/author-environment-install.d.ts +14 -0
  7. package/dist/author-environment-install.js +104 -0
  8. package/dist/author-environment-source.d.ts +162 -0
  9. package/dist/author-environment-source.js +226 -0
  10. package/dist/author-install.d.ts +22 -0
  11. package/dist/author-install.js +289 -0
  12. package/dist/author-reference.d.ts +1 -1
  13. package/dist/author-reference.js +23 -4
  14. package/dist/cli.js +56 -23
  15. package/dist/command-discovery.d.ts +3 -0
  16. package/dist/command-discovery.js +122 -0
  17. package/dist/content-query.js +4 -1
  18. package/dist/content-workspace.d.ts +2 -138
  19. package/dist/content-workspace.js +6 -6
  20. package/dist/debug-environment-install.d.ts +15 -0
  21. package/dist/debug-environment-install.js +130 -0
  22. package/dist/debug-environments.d.ts +135 -0
  23. package/dist/debug-environments.js +48 -0
  24. package/dist/demo.js +22 -8
  25. package/dist/desktop-cli.d.ts +3 -0
  26. package/dist/desktop-cli.js +72 -0
  27. package/dist/desktop-client.d.ts +71 -0
  28. package/dist/desktop-client.js +162 -0
  29. package/dist/environment-demo.d.ts +8 -0
  30. package/dist/environment-demo.js +52 -0
  31. package/dist/environment-rules.js +38 -19
  32. package/dist/environment.d.ts +12 -8
  33. package/dist/environment.js +107 -58
  34. package/dist/init.d.ts +1 -0
  35. package/dist/init.js +125 -0
  36. package/dist/jobs.d.ts +3 -1
  37. package/dist/jobs.js +34 -15
  38. package/dist/managed-projects.d.ts +7 -3
  39. package/dist/managed-projects.js +10 -6
  40. package/dist/mcp-contracts.d.ts +28 -1
  41. package/dist/mcp-contracts.js +24 -1
  42. package/dist/mcp.js +21 -7
  43. package/dist/official-environment-packages.d.ts +6 -0
  44. package/dist/official-environment-packages.js +19 -0
  45. package/dist/official-environments.d.ts +7 -0
  46. package/dist/official-environments.js +25 -0
  47. package/dist/pack-project.d.ts +1 -0
  48. package/dist/pack-project.js +66 -0
  49. package/dist/package-updates.d.ts +10 -3
  50. package/dist/package-updates.js +71 -21
  51. package/dist/prepared-document.d.ts +1 -0
  52. package/dist/prepared-document.js +5 -13
  53. package/dist/preview-control.js +24 -1
  54. package/dist/preview.d.ts +1 -0
  55. package/dist/preview.js +6 -4
  56. package/dist/project.d.ts +1 -0
  57. package/dist/project.js +57 -18
  58. package/dist/template/README.md +8 -8
  59. package/dist/template/package.json +2 -2
  60. package/dist/template/skills/arcadia-content-authoring/SKILL.md +15 -2
  61. package/dist/template/skills/arcadia-content-authoring/references/tool-workflows.md +25 -1
  62. package/dist/testing.d.ts +3 -4
  63. package/dist/testing.js +22 -8
  64. package/dist/workspace-cli.js +6 -4
  65. package/dist/workspace.d.ts +1 -0
  66. package/dist/workspace.js +66 -15
  67. package/package.json +10 -5
@@ -1,11 +1,44 @@
1
+ import { sha256Hex } from '@arcadia-eternity/const';
1
2
  import { catalogMaterialDigest } from '@arcadia-eternity/pack-loader/node';
3
+ import { officialEnvironmentCatalog } from './official-environments.js';
2
4
  import semver from 'semver';
3
5
  import { mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
4
- import { join } from 'node:path';
6
+ import { dirname, join } from 'node:path';
5
7
  import { tmpdir } from 'node:os';
6
8
  import { acquireSource } from './managed-sources.js';
7
9
  import { errorCode, isRecord } from './types.js';
8
10
  export const officialPackage = '@arcadia-eternity/data-pack-base';
11
+ export function startAutomaticContentUpdates(update, onError) {
12
+ const controller = new AbortController();
13
+ let running;
14
+ let timer;
15
+ function schedule(delay) {
16
+ timer = setTimeout(() => {
17
+ running = check();
18
+ }, delay);
19
+ timer.unref();
20
+ }
21
+ async function check() {
22
+ let delay = 6 * 60 * 60 * 1000;
23
+ try {
24
+ await update({ signal: controller.signal });
25
+ }
26
+ catch (error) {
27
+ if (controller.signal.aborted)
28
+ return;
29
+ onError(error);
30
+ delay = 15 * 60 * 1000;
31
+ }
32
+ if (!controller.signal.aborted)
33
+ schedule(delay);
34
+ }
35
+ schedule(3000);
36
+ return () => {
37
+ controller.abort();
38
+ clearTimeout(timer);
39
+ return running;
40
+ };
41
+ }
9
42
  export function selectPackageUpdate(metadata, name, current, client) {
10
43
  if (!isRecord(metadata) ||
11
44
  metadata.name !== name ||
@@ -43,11 +76,17 @@ export function selectPackageUpdate(metadata, name, current, client) {
43
76
  }
44
77
  return null;
45
78
  }
46
- export async function findPackageUpdate(name, current, client) {
47
- const response = await fetch('https://registry.npmjs.org/' + encodeURIComponent(name), {
48
- headers: { Accept: 'application/vnd.npm.install-v1+json' },
79
+ export async function findPackageUpdate(name, current, client, signal) {
80
+ const url = 'https://registry.npmjs.org/' + encodeURIComponent(name);
81
+ const metadata = await registryJson(url, 'application/vnd.npm.install-v1+json', signal);
82
+ return selectPackageUpdate(metadata, name, current, client);
83
+ }
84
+ async function registryJson(url, accept, signal) {
85
+ const timeout = AbortSignal.timeout(20000);
86
+ const response = await fetch(url, {
87
+ headers: { Accept: accept },
49
88
  redirect: 'error',
50
- signal: AbortSignal.timeout(20000),
89
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
51
90
  });
52
91
  if (!response.ok)
53
92
  throw new Error('无法检查 npm 包更新(HTTP ' + response.status + ')');
@@ -65,7 +104,7 @@ export async function findPackageUpdate(name, current, client) {
65
104
  throw new Error('npm 版本清单过大');
66
105
  chunks.push(chunk);
67
106
  }
68
- return selectPackageUpdate(JSON.parse(Buffer.concat(chunks).toString('utf8')), name, current, client);
107
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
69
108
  }
70
109
  async function acquireOfficial(candidate, destination, signal) {
71
110
  if (candidate.name !== officialPackage ||
@@ -85,12 +124,14 @@ async function acquireOfficial(candidate, destination, signal) {
85
124
  manifest.arcadia?.projectId !== 'base' ||
86
125
  manifest.arcadia?.namespace !== 'base')
87
126
  throw new Error('INVALID_OFFICIAL_PACKAGE');
88
- return directory;
127
+ const catalog = await officialEnvironmentCatalog(candidate.version, name => registryJson('https://registry.npmjs.org/' + encodeURIComponent(name) + '/' + candidate.version, 'application/json', signal));
128
+ return { directory, catalog };
89
129
  }
90
130
  export async function withOfficialUpdateDirectory(candidate, signal, use) {
91
131
  const stage = await mkdtemp(join(tmpdir(), 'arcadia-official-update-'));
92
132
  try {
93
- return await use(await acquireOfficial(candidate, join(stage, 'source'), signal));
133
+ const { directory, catalog } = await acquireOfficial(candidate, join(stage, 'source'), signal);
134
+ return await use(directory, catalog);
94
135
  }
95
136
  finally {
96
137
  await rm(stage, { recursive: true, force: true });
@@ -116,7 +157,7 @@ export async function selectServerBase(store, shipped, host, pin, validate) {
116
157
  });
117
158
  const candidates = entries
118
159
  .filter(entry => entry.isDirectory() && semver.valid(entry.name) === entry.name)
119
- .map(entry => ({ directory: join(store, entry.name), version: entry.name, cached: true }));
160
+ .map(entry => ({ directory: join(store, entry.name, 'package'), version: entry.name, cached: true }));
120
161
  if (bundledCompatible)
121
162
  candidates.push(fallback);
122
163
  // Inspect cached ties first to detect an ambiguous release while retaining the shipped reference.
@@ -134,11 +175,10 @@ export async function selectServerBase(store, shipped, host, pin, validate) {
134
175
  if (!manifest.engines?.arcadia?.trim() || !semver.satisfies(host, manifest.engines.arcadia))
135
176
  continue;
136
177
  const digest = await catalogMaterialDigest(directory);
137
- const recorded = await readFile(join(directory, '.arcadia-material-digest'), 'utf8').catch(error => {
138
- if (errorCode(error) !== 'ENOENT')
139
- throw error;
140
- });
141
- if (recorded !== undefined && digest !== recorded)
178
+ const release = dirname(directory);
179
+ const catalog = await readFile(join(release, 'official-environments.json'), 'utf8');
180
+ const recorded = await readFile(join(release, '.arcadia-release-digest'), 'utf8');
181
+ if (sha256Hex(digest, '\0', catalog) !== recorded)
142
182
  throw new Error('OFFICIAL_MATERIAL_DIGEST_MISMATCH');
143
183
  if (version === bundled.version && bundledCompatible) {
144
184
  if (digest !== (await catalogMaterialDigest(shipped)))
@@ -158,24 +198,34 @@ export async function selectServerBase(store, shipped, host, pin, validate) {
158
198
  cause: lastError,
159
199
  });
160
200
  }
161
- export async function installServerBaseUpdate(store, candidate, host, validate) {
201
+ export async function installServerBaseUpdate(store, candidate, host, validate, options = {}) {
162
202
  if (!semver.satisfies(host, candidate.range))
163
203
  throw new Error('INCOMPATIBLE_OFFICIAL_PACKAGE');
164
204
  await mkdir(store, { recursive: true, mode: 0o700 });
165
205
  const stage = await mkdtemp(join(store, '.install-'));
166
206
  try {
167
- const directory = await acquireOfficial(candidate, join(stage, 'source'), AbortSignal.timeout(120000));
168
- await validate(directory);
169
- const digest = await catalogMaterialDigest(directory);
170
- await writeFile(join(directory, '.arcadia-material-digest'), digest);
207
+ const timeout = AbortSignal.timeout(120000);
208
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
209
+ const release = join(stage, 'release');
210
+ const { directory, catalog } = await acquireOfficial(candidate, release, signal);
211
+ const catalogText = JSON.stringify(catalog);
212
+ await writeFile(join(release, 'official-environments.json'), catalogText);
213
+ await validate(directory, signal);
214
+ const digest = sha256Hex(await catalogMaterialDigest(directory), '\0', catalogText);
215
+ await writeFile(join(release, '.arcadia-release-digest'), digest);
216
+ signal.throwIfAborted();
217
+ await options.beforeCommit?.(directory);
218
+ options.signal?.throwIfAborted();
171
219
  try {
172
- await rename(directory, join(store, candidate.version));
220
+ await rename(release, join(store, candidate.version));
173
221
  }
174
222
  catch (error) {
175
223
  // Concurrent installers can only publish a complete, verified directory at this version.
176
224
  if (!['EEXIST', 'ENOTEMPTY'].includes(errorCode(error) ?? ''))
177
225
  throw error;
178
- if ((await catalogMaterialDigest(join(store, candidate.version))) !== digest)
226
+ const installed = join(store, candidate.version);
227
+ const installedDigest = sha256Hex(await catalogMaterialDigest(join(installed, 'package')), '\0', await readFile(join(installed, 'official-environments.json'), 'utf8'));
228
+ if (installedDigest !== digest)
179
229
  throw new Error('OFFICIAL_BASE_VERSION_CONFLICT: ' + candidate.version, { cause: error });
180
230
  }
181
231
  }
@@ -1,3 +1,4 @@
1
+ export { environmentProjectDocument } from './debug-environments.js';
1
2
  import { type UnknownRecord } from './types.js';
2
3
  export declare function parseManifestDraft(text: string): {
3
4
  document: {
@@ -1,20 +1,12 @@
1
1
  import { sha256Hex } from '@arcadia-eternity/const';
2
2
  import { readFile, realpath } from 'node:fs/promises';
3
3
  import { join, resolve } from 'node:path';
4
- import { normalizeEnvironmentDocument } from './debug-environments.js';
4
+ import { environmentManifestDocument, environmentProjectDocument, normalizeEnvironmentDocument, } from './debug-environments.js';
5
+ export { environmentProjectDocument } from './debug-environments.js';
5
6
  import { contentError, readJson } from './workspace-materials.js';
6
- import { errorCode, isRecord } from './types.js';
7
+ import { errorCode } from './types.js';
7
8
  export function parseManifestDraft(text) {
8
- const manifest = JSON.parse(text);
9
- if (!isRecord(manifest.arcadiaEnvironment) || !isRecord(manifest.dependencies))
10
- throw contentError('ENVIRONMENT_MANIFEST_INVALID');
11
- const sources = manifest.arcadiaEnvironment.sources;
12
- if (!Array.isArray(sources))
13
- throw contentError('ENVIRONMENT_MANIFEST_INVALID');
14
- const document = normalizeEnvironmentDocument({
15
- ...manifest.arcadiaEnvironment,
16
- packages: Object.fromEntries(Object.entries(manifest.dependencies).filter(([name]) => !sources.includes(name))),
17
- });
9
+ const document = environmentProjectDocument(JSON.parse(text));
18
10
  return { document, revision: sha256Hex(text) };
19
11
  }
20
12
  export function preparedDocument(metadata, legacyManifest) {
@@ -68,7 +60,7 @@ export async function readInstalledEnvironmentDocument(directory, contentRevisio
68
60
  throw contentError('ENVIRONMENT_MANIFEST_INVALID');
69
61
  if (selected)
70
62
  throw contentError('ENVIRONMENT_PRESET_AMBIGUOUS', '项目依赖多个环境包,请显式选择环境声明。');
71
- selected = parseManifestDraft(JSON.stringify(pkg)).document;
63
+ selected = environmentManifestDocument(pkg);
72
64
  }
73
65
  return selected;
74
66
  }
@@ -3,7 +3,7 @@ import { isDeepStrictEqual } from 'node:util';
3
3
  import { WorkspaceError } from './workspace.js';
4
4
  import { playersFromTeams } from './project-teams.js';
5
5
  import { errorCode, errorMessage, isRecord } from './types.js';
6
- const operations = new Set(['create', 'read', 'events', 'action', 'reset', 'close']);
6
+ const operations = new Set(['create', 'read', 'events', 'action', 'reset', 'close', 'team-validate']);
7
7
  const idPattern = /^[a-z0-9][a-z0-9_-]{0,79}$/;
8
8
  function fail(code, message) {
9
9
  throw new WorkspaceError(code, message);
@@ -141,6 +141,29 @@ export class PreviewAutomation {
141
141
  };
142
142
  }
143
143
  async #call(operation, input) {
144
+ if (operation === 'team-validate') {
145
+ if (typeof input.teamId !== 'string' || !idPattern.test(input.teamId))
146
+ fail('TEAM_INVALID', '需要已保存的队伍标识');
147
+ const team = (await this.readTeams()).find(entry => entry.id === input.teamId);
148
+ if (!team)
149
+ fail('TEAM_MISSING', `未找到已保存的队伍 ${input.teamId}`);
150
+ const { environmentId, environmentRevision } = this.prepared.candidate;
151
+ const identity = { teamId: team.id, teamVersion: team.version, environmentId, environmentRevision };
152
+ try {
153
+ this.prepared.assertTeam(team.team);
154
+ return { ...identity, valid: true };
155
+ }
156
+ catch (error) {
157
+ return {
158
+ ...identity,
159
+ valid: false,
160
+ diagnostic: {
161
+ code: errorCode(error) ?? 'TEAM_INVALID',
162
+ message: isRecord(error) && typeof error.detail === 'string' ? error.detail : errorMessage(error),
163
+ },
164
+ };
165
+ }
166
+ }
144
167
  if (operation === 'create') {
145
168
  if (this.#sessions.size >= 4)
146
169
  fail('BATTLE_SESSION_LIMIT', '请先关闭一个自动调试对局(最多四个)');
package/dist/preview.d.ts CHANGED
@@ -21,4 +21,5 @@ export declare function startPreview(root: string, { clientUrl, signal, ...envir
21
21
  closed: boolean;
22
22
  }>;
23
23
  export declare function previewCommand(): Promise<void>;
24
+ export declare function readSourceMappings(root: string): Promise<Record<string, string | undefined>>;
24
25
  export {};
package/dist/preview.js CHANGED
@@ -303,10 +303,12 @@ export async function previewCommand() {
303
303
  const preview = await startPreview(process.cwd(), {
304
304
  clientUrl: process.env.ARCADIA_PREVIEW_CLIENT_URL,
305
305
  signal: controller.signal,
306
- environmentId: process.env.ARCADIA_DEBUG_ENVIRONMENT ?? 'default',
307
- offline: !process.env.ARCADIA_DEBUG_ENVIRONMENT || process.env.ARCADIA_DEBUG_ENVIRONMENT === 'default',
306
+ environmentId: process.env.ARCADIA_DEBUG_ENVIRONMENT,
307
+ offline: process.env.ARCADIA_DEBUG_ENVIRONMENT && process.env.ARCADIA_DEBUG_ENVIRONMENT !== 'default'
308
+ ? false
309
+ : undefined,
308
310
  lockRoot: process.env.ARCADIA_DEBUG_ROOT,
309
- sources: process.env.ARCADIA_DEBUG_ROOT ? await readSourceMappings(process.env.ARCADIA_DEBUG_ROOT) : {},
311
+ sources: await readSourceMappings(process.env.ARCADIA_DEBUG_ROOT ?? process.cwd()),
310
312
  });
311
313
  const { endpoint, clientPath, candidate, environmentLock, sourceRevisions, url } = preview;
312
314
  console.log(`ARCADIA_RESULT=${JSON.stringify({ preview: { endpoint, clientPath, url }, candidate, environmentLock, sourceRevisions })}`);
@@ -320,7 +322,7 @@ export async function previewCommand() {
320
322
  process.removeListener('disconnect', stop);
321
323
  }
322
324
  }
323
- async function readSourceMappings(root) {
325
+ export async function readSourceMappings(root) {
324
326
  try {
325
327
  return JSON.parse(await readFile(join(root, '.arcadia/debug-sources.json'), 'utf8'));
326
328
  }
package/dist/project.d.ts CHANGED
@@ -16,5 +16,6 @@ export declare function authorConnection(root: string, execute?: boolean, env?:
16
16
  export declare function connectDevelopmentSdk(root: string): Promise<{
17
17
  linked: string[];
18
18
  }>;
19
+ export declare function copyAuthorSkill(directory: string): Promise<void>;
19
20
  export declare function createSourceProject(directory: string, identity: string, arcadiaRange?: string): Promise<string>;
20
21
  export declare function updateAuthorLock(workspace: AuthorWorkspace): Promise<void>;
package/dist/project.js CHANGED
@@ -1,12 +1,13 @@
1
1
  import { cp, lstat, mkdir, mkdtemp, rm, readFile, realpath, readdir, symlink, writeFile } from 'node:fs/promises';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { ManagedProjects } from './managed-projects.js';
4
- import { dirname, join } from 'node:path';
4
+ import { dirname, join, relative } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { createRequire } from 'node:module';
7
7
  import { WorkspaceError, normalizeArcadiaRange } from './workspace.js';
8
8
  import { siblingModulePath } from './module-path.js';
9
9
  import { errorCode } from './types.js';
10
+ import { persistentSdkPackages } from './appimage-sdk.js';
10
11
  const require = createRequire(import.meta.url);
11
12
  const moduleRoot = fileURLToPath(new URL('../', import.meta.url));
12
13
  export function authorConnection(root, execute = false, env = process.env, readOnly = false, contextFile, published = false) {
@@ -73,26 +74,40 @@ export async function connectDevelopmentSdk(root) {
73
74
  await directory(['node_modules']);
74
75
  await directory(['node_modules', '@arcadia-eternity']);
75
76
  await directory(['node_modules', '.bin']);
76
- const packages = {
77
+ const sources = {
77
78
  '@arcadia-eternity/battle': await packageRoot('@arcadia-eternity/battle', '@arcadia-eternity/battle/engine'),
78
79
  '@arcadia-eternity/pack-loader': await packageRoot('@arcadia-eternity/pack-loader', '@arcadia-eternity/pack-loader/node'),
79
80
  '@arcadia-eternity/content-sdk': moduleRoot,
80
81
  typescript: await packageRoot(['typescript', 'typescript-native-bridge'], 'typescript'),
81
82
  };
83
+ let connected;
84
+ const packages = () => (connected ??= persistentSdkPackages(sources));
85
+ async function missing(target) {
86
+ try {
87
+ await lstat(target);
88
+ return false;
89
+ }
90
+ catch (error) {
91
+ if (errorCode(error) !== 'ENOENT')
92
+ throw error;
93
+ return true;
94
+ }
95
+ }
82
96
  const linked = [];
83
- for (const [name, source] of Object.entries(packages)) {
97
+ for (const name of Object.keys(sources)) {
84
98
  const target = join(root, 'node_modules', name);
85
99
  await directory(['node_modules', ...name.split('/').slice(0, -1)]);
86
- try {
87
- await lstat(target);
100
+ if (!(await missing(target)))
88
101
  continue;
102
+ const source = (await packages())[name];
103
+ try {
104
+ await symlink(source, target, process.platform === 'win32' ? 'junction' : 'dir');
105
+ linked.push(name);
89
106
  }
90
107
  catch (error) {
91
- if (errorCode(error) !== 'ENOENT')
108
+ if (errorCode(error) !== 'EEXIST')
92
109
  throw error;
93
110
  }
94
- await symlink(source, target, process.platform === 'win32' ? 'junction' : 'dir');
95
- linked.push(name);
96
111
  }
97
112
  // npm scripts use the shared CLI, while the desktop invokes its absolute entry directly.
98
113
  const bin = join(root, 'node_modules/.bin');
@@ -101,32 +116,55 @@ export async function connectDevelopmentSdk(root) {
101
116
  ['arcadia-content', 'cli'],
102
117
  ['arcadia-content-mcp', 'mcp'],
103
118
  ]) {
104
- const script = siblingModulePath(entry);
119
+ const target = join(bin, process.platform === 'win32' ? name + '.cmd' : name);
120
+ if (!(await missing(target)))
121
+ continue;
122
+ const script = join((await packages())['@arcadia-eternity/content-sdk'], relative(moduleRoot, siblingModulePath(entry)));
105
123
  if (process.platform === 'win32')
106
- await writeFile(join(bin, name + '.cmd'), `@echo off\r\nnode "${script}" %*\r\n`, { flag: 'wx' }).catch(e => {
124
+ await writeFile(target, `@echo off\r\nnode "${script}" %*\r\n`, { flag: 'wx' }).catch(e => {
107
125
  if (errorCode(e) !== 'EEXIST')
108
126
  throw e;
109
127
  });
110
128
  else
111
- await symlink(script, join(bin, name)).catch(e => {
129
+ await symlink(script, target).catch(e => {
112
130
  if (errorCode(e) !== 'EEXIST')
113
131
  throw e;
114
132
  });
115
133
  }
116
134
  return { linked };
117
135
  }
136
+ async function templateDirectory() {
137
+ const bundled = fileURLToPath(new URL('./template/', import.meta.url));
138
+ try {
139
+ await lstat(bundled);
140
+ return bundled;
141
+ }
142
+ catch (error) {
143
+ if (errorCode(error) !== 'ENOENT')
144
+ throw error;
145
+ return fileURLToPath(new URL('../template/', import.meta.url));
146
+ }
147
+ }
148
+ export async function copyAuthorSkill(directory) {
149
+ const name = 'arcadia-content-authoring';
150
+ let source = join(await templateDirectory(), 'skills', name);
151
+ try {
152
+ await lstat(source);
153
+ }
154
+ catch (error) {
155
+ if (errorCode(error) !== 'ENOENT')
156
+ throw error;
157
+ source = fileURLToPath(new URL('../../../docs/guides/ugc-authoring-agent/', import.meta.url));
158
+ }
159
+ await mkdir(join(directory, 'skills'), { recursive: true });
160
+ await cp(source, join(directory, 'skills', name), { recursive: true });
161
+ }
118
162
  export async function createSourceProject(directory, identity, arcadiaRange = '^' + require('../package.json').version) {
119
163
  if (!/^[a-z0-9][a-z0-9-]{0,79}$/.test(identity))
120
164
  throw new WorkspaceError('PROJECT_INVALID', '项目 ID 无效');
121
165
  const range = normalizeArcadiaRange(arcadiaRange);
122
166
  await mkdir(directory); // No overwrite or merge with existing directories.
123
- let template = fileURLToPath(new URL('./template/', import.meta.url));
124
- try {
125
- await lstat(template);
126
- }
127
- catch {
128
- template = fileURLToPath(new URL('../template/', import.meta.url));
129
- }
167
+ const template = await templateDirectory();
130
168
  for (const entry of await readdir(template))
131
169
  await cp(join(template, entry), join(directory, entry === 'gitignore-template'
132
170
  ? '.gitignore'
@@ -149,6 +187,7 @@ export async function createSourceProject(directory, identity, arcadiaRange = '^
149
187
  }
150
188
  }
151
189
  await renameText(directory);
190
+ await copyAuthorSkill(directory);
152
191
  for (const script of ['release-payload.mjs', 'release-test-npm.mjs'])
153
192
  await cp(fileURLToPath(new URL('../' + script, import.meta.url)), join(directory, '.github/scripts', script));
154
193
  const manifest = JSON.parse(await readFile(join(directory, 'package.json'), 'utf8'));
@@ -8,14 +8,14 @@
8
8
 
9
9
  让助手按任务读取项目中的技能。
10
10
 
11
- | 任务 | 文件 |
12
- | ------------------------ | ------------------------------------------- |
13
- | 创作内容、编写效果和测试 | `skills/arcadia-content-authoring/SKILL.md` |
14
- | 根据资料复刻精灵 | `skills/seer2-recreate-pet/SKILL.md` |
15
- | 提交或同步源码 | `skills/arcadia-content-git/SKILL.md` |
16
- | 检查发行归档、发布版本 | `skills/arcadia-content-release/SKILL.md` |
17
-
18
- 已有项目可通过新版 MCP 的 `author_reference` 读取 `git` 或 `release` 主题,也可直接读取已安装 SDK 的 `dist/template/skills/` 目录。
11
+ | 任务 | 文件 |
12
+ | ---------------------------------------- | ------------------------------------------- |
13
+ | 初始化包或环境、调试赛制、编写效果和测试 | `skills/arcadia-content-authoring/SKILL.md` |
14
+ | 根据资料复刻精灵 | `skills/seer2-recreate-pet/SKILL.md` |
15
+ | 提交或同步源码 | `skills/arcadia-content-git/SKILL.md` |
16
+ | 检查发行归档、发布版本 | `skills/arcadia-content-release/SKILL.md` |
17
+
18
+ 已有项目可通过新版 MCP 的 `author_reference` 读取 `authoring`、`git` 或 `release` 主题,也可直接读取已安装 SDK 的 `dist/template/skills/` 目录。
19
19
 
20
20
  ## 分离的表现与资源(v2)
21
21
 
@@ -21,7 +21,7 @@
21
21
  "devDependencies": {
22
22
  "@types/node": "26.6.6",
23
23
  "typescript": "6.0.3",
24
- "@arcadia-eternity/content-sdk": "4.12.0",
24
+ "@arcadia-eternity/content-sdk": "4.14.0",
25
25
  "fflate": "0.8.3"
26
26
  },
27
27
  "arcadia": {
@@ -38,6 +38,6 @@
38
38
  "license": "MIT",
39
39
  "engines": {
40
40
  "node": ">=24 <25",
41
- "arcadia": "^4.12.0"
41
+ "arcadia": "^4.14.0"
42
42
  }
43
43
  }
@@ -1,11 +1,24 @@
1
1
  ---
2
2
  name: arcadia-content-authoring
3
- description: Build or debug an Arcadia Eternity npm content pack with TypeScript effects and real-engine tests. Use when creating or modifying a content pack, its effects, or its local test and preview workflow.
3
+ description: Create and debug Arcadia Eternity content packs and standalone battle environments. Use for CLI project initialization, rules and dependencies, team admission, fixed-seed battles, TypeScript effects and local previews.
4
4
  ---
5
5
 
6
6
  # Arcadia content authoring
7
7
 
8
- Work in the author's content project. Ask for the desired game behavior when its trigger, target or lifetime is ambiguous. Use the SDK and host version actually available to the project; `arcadia.sdkApi` is an API compatibility version, not an engine build identity.
8
+ ## Choose a project
9
+
10
+ For new species, skills, marks or effects, run `arcadia-content init pack <directory>`. For a tournament format or a combination of existing packages, run `arcadia-content init environment <directory>`. Use a new or empty directory. When editing an existing project, inspect its `package.json` and run `arcadia-content workspace <directory> describe`. A content pack declares `arcadia`. A standalone environment declares `arcadiaEnvironment` and lists its content packages in npm `dependencies`.
11
+
12
+ ## Debug a standalone environment
13
+
14
+ 1. Read the environment with `environment_list` and its schema with `author_reference` topic `environment`. Keep the current ID and package selections when changing a rule. Pass the returned version as `expectedVersion` to `environment_save`. The rule declaration, capability requirements and package versions together determine what to test.
15
+ 2. Save test teams with `team_save` or edit `debug/teams/*.yaml`. Use species and skills from the declared packages. For a ban, prepare two legal teams and a third that violates just the proposed restriction.
16
+ 3. Start `arcadia-content workspace <directory> preview --execute` or connect `arcadia-content-mcp <directory> --execute` and call `preview_start`. The environment project itself supplies the rules and members. Poll `job_get` on MCP until the preview succeeds. Call `team_validate` with that preview’s `jobId` and each saved `teamId`. Check `valid` and record the diagnostic for the intended violation. Then use `battle_create` with the two legal team IDs and a fixed seed.
17
+ 4. Prepare a fresh preview after changing rules or dependencies. Record the tested environment ID, revision, teams, seed and observed result. Stop the preview with Ctrl+C or `job_cancel`. When an installable archive is requested, run `arcadia-content workspace <directory> pack --execute` or call `package_build`. In the desktop environment library, choose **安装环境包** to install the resulting .tgz or an exact npm version. Local play switches when the user chooses **本地使用**. See the [CLI and MCP workflows](references/tool-workflows.md) for event inspection and conflict handling.
18
+
19
+ ## Author a content pack
20
+
21
+ Work in the author's content project. Ask for the desired game behavior when its trigger, target or lifetime is ambiguous. Use the SDK and host version available to the project. `arcadia.sdkApi` identifies the compatible SDK API.
9
22
 
10
23
  1. Read `package.json` and the actual source layout: `data/species`, `data/skills`, `data/marks`, `src`, `assets`, `locales`, `test` and `arcadia.config.mjs`. Some older projects still use a root `content.json`; follow their manifest rather than assuming it. Do not edit generated `dist` as source. If the host repository is available, consult `docs/guides/npm-content.md` and `docs/guides/effect-sdk.md`. Do not assume SDK packages have been published merely because a version is in a manifest.
11
24
  2. Declare behavior with `@effect` and `@on` in `src/effects/*.effect.ts`; for parameters or bindings use a decorated class with `static create(context)` returning `defineCodeEffect`. The SDK discovers files and builds `effectArtifact`. Use canonical prototypes from the current context. Keep `projectId`, namespace, use IDs and binding keys stable unless a breaking identity change is intended. Cross-package data references require npm dependencies.
@@ -1,5 +1,29 @@
1
1
  # Author tool workflows
2
2
 
3
+ ## Start from a directory
4
+
5
+ To create a content pack, run `arcadia-content init pack frost-pack`. To build a ruleset from existing packages, initialize an independent environment and exercise it directly:
6
+
7
+ ```sh
8
+ arcadia-content init environment singles-cup
9
+ arcadia-content workspace singles-cup describe
10
+ arcadia-content workspace singles-cup check
11
+ arcadia-content workspace singles-cup demo --execute --seed cup-baseline
12
+ arcadia-content workspace singles-cup preview --execute
13
+ ```
14
+
15
+ The static check validates the environment declaration, requirements and rules. The demo prepares the dependencies and runs the saved `blue` and `orange` teams. A matching local official base can be reused. Other registry packages may need a network connection on the first run. The preview stays open for the interactive client until Ctrl+C.
16
+
17
+ For MCP, launch `arcadia-content-mcp singles-cup --execute` and use `workspace_describe` to inspect the session. `demo_start` accepts a seed. After `preview_start` succeeds, call `team_validate` with `{jobId, teamId}` to check one saved team against the frozen preview without opening a battle. The result identifies `teamId`, `teamVersion`, `environmentId` and `environmentRevision`. A rule rejection is a normal result with `valid: false` and a diagnostic code and message. For example, validate two otherwise legal teams on opposite sides of a size limit, then use `battle_create` with two admitted teams and a seed.
18
+
19
+ The CLI accepts the same JSON on stdin while the preview from that project is running:
20
+
21
+ ```sh
22
+ printf '%s' '{"jobId":"<preview-job-id>","teamId":"blue"}' | arcadia-content workspace singles-cup team-validate
23
+ ```
24
+
25
+ ## Edit a content pack
26
+
3
27
  Start with `arcadia-content workspace <directory> describe` or MCP `workspace_describe`. Use the returned SDK API, capabilities and source revision. Opening or inspecting a project does not import its effect code.
4
28
 
5
29
  The CLI emits JSON. `query`, `read`, `write` and `save` take JSON on stdin:
@@ -30,7 +54,7 @@ Build/check/test use the fixed author commands. A headless demo proves engine ex
30
54
 
31
55
  `content_query` searches localized names and accepts exact `id`, `contentKind`, `locale`, `namespace`, `packageName` and `scope: project | dependencies | all`. Default summaries omit the full record. Request `detail: full` before editing; use `nextOffset` to continue. Locale pages contain individual objects, not whole files. Declared installed dependencies are read without executing effects and return read-only provenance. Their file paths are relative to those packages, not valid bound-project edit targets. Missing or ambiguous dependencies are diagnostics, not permission to guess a target.
32
56
 
33
- Use `team_list`/`team_save`/`team_remove` and `environment_list`/`environment_save` for saved project data. Saves require `expectedVersion`; null creates a file. These operations never select a team/environment, overwrite local drafts, or mutate a running match. Desktop file-change notifications refresh clean views promptly without focus changes; dirty drafts retain their base and show external-change conflicts. Users explicitly reload or resolve drafts. Environment changes require preparing a new candidate before a new battle.
57
+ Use `team_list`/`team_save`/`team_remove` for saved project teams. New teams and named debug environments inside a content pack use `expectedVersion: null`. For an existing environment, read `environment_list` and save the document with its returned version as `expectedVersion`. The standalone environment document represents the root npm manifest. A saved change takes effect in a fresh preview. Desktop file-change notifications refresh clean views promptly without focus changes; dirty drafts retain their base and show external-change conflicts.
34
58
 
35
59
  `author_reference` and `arcadia://authoring/<topic>` expose actual SDK schemas/examples. Schema and content topics include species, skills, marks, team, environment, descriptions and effects. For repository tasks, read the `git` skill through the same tool. For release preparation or publication, read `release`. Read schema stage notes: linked-runtime schema is not source syntax. `asset_inspect` takes a declared resource ID; `includeImage: true` returns local image bytes up to 2 MiB as standard MCP image content. Use an image filename extension: MIME types follow filenames, and unknown extensions remain metadata-only. The client handles decoding/display; this tool does not validate image integrity or report dimensions. Large images remain metadata-only; no automatic thumbnail is generated. HTTP assets are not downloaded; audio/SWF are metadata only.
36
60
 
package/dist/testing.d.ts CHANGED
@@ -5,7 +5,7 @@ import type { Battle } from '@arcadia-eternity/battle/engine';
5
5
  export { prepareBattleEnvironment } from './environment.js';
6
6
  import { UseSkillContext } from '@arcadia-eternity/battle/engine';
7
7
  export { AttackTargetOpinion, EffectContext, EffectTrigger, RemoveMarkContext, parameterAddress, setGlobalLogger, } from '@arcadia-eternity/battle/engine';
8
- /** Existing package scenarios use the default environment with declared dependencies only. */
8
+ /** Prepare a captured author project with its selected environment and saved teams. */
9
9
  export declare function prepareContentPack(root?: string, options?: NonNullable<Parameters<typeof prepareBattleEnvironment>[1]>): Promise<{
10
10
  environment: Readonly<import("@arcadia-eternity/pack-loader/node").PreparedNpmEnvironment>;
11
11
  environmentDocument: import("./debug-environments.js").EnvironmentDocumentV2;
@@ -19,12 +19,11 @@ export declare function prepareContentPack(root?: string, options?: NonNullable<
19
19
  loadTeams(ids: string[]): ReturnType<typeof playersFromTeams>;
20
20
  teams: import("./project-teams.js").ProjectTeam[];
21
21
  teamVersions: Record<string, string | null>;
22
- manifest: import("./workspace.js").PackageManifest & {
23
- arcadia: import("./workspace.js").ManifestArcadia;
24
- };
22
+ manifest: import("./workspace.js").PackageManifest;
25
23
  files: string[];
26
24
  track(battle: import("./environment.js").BattleLike): void;
27
25
  untrack(battle: import("./environment.js").BattleLike): void;
26
+ assertTeam: (team: readonly unknown[]) => void;
28
27
  createBattle: (seed?: string, { ai, players: supplied, runtimeIds, battleOptions, }?: {
29
28
  ai?: boolean;
30
29
  players?: readonly unknown[];
package/dist/testing.js CHANGED
@@ -9,19 +9,25 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
9
9
  import assert from 'node:assert/strict';
10
10
  import { resolveEnvironmentBattleOptions } from '@arcadia-eternity/const';
11
11
  import { randomBytes } from 'node:crypto';
12
+ import { readFile } from 'node:fs/promises';
12
13
  import { join, resolve } from 'node:path';
13
14
  import { pathToFileURL } from 'node:url';
14
15
  import { prepareBattleEnvironment } from './environment.js';
15
16
  import { assertPlayableTeam, resolveEnvironmentMechanics, validateEnvironmentRules } from './environment-rules.js';
16
17
  import { prepareSandboxContent } from '@arcadia-eternity/battle/sandbox/effects';
17
18
  import { createNodeBattleWorkerManager } from '@arcadia-eternity/battle/sandbox/node';
18
- import { isRecord } from './types.js';
19
+ import { errorCode, isRecord } from './types.js';
19
20
  export { prepareBattleEnvironment } from './environment.js';
20
21
  import { AttackTargetOpinion, BattleMessageType, TurnContext, UseSkillContext } from '@arcadia-eternity/battle/engine';
21
22
  export { AttackTargetOpinion, EffectContext, EffectTrigger, RemoveMarkContext, parameterAddress, setGlobalLogger, } from '@arcadia-eternity/battle/engine';
22
- /** Existing package scenarios use the default environment with declared dependencies only. */
23
- export async function prepareContentPack(root = process.cwd(), options = {}) {
24
- root = resolve(root);
23
+ async function defaultTeamIds(root) {
24
+ const manifest = JSON.parse(await readFile(join(root, 'package.json'), 'utf8').catch(error => {
25
+ if (errorCode(error) !== 'ENOENT')
26
+ throw error;
27
+ return '{}';
28
+ }));
29
+ if (!manifest.arcadia && Object.hasOwn(manifest, 'arcadiaEnvironment'))
30
+ return ['blue', 'orange'];
25
31
  const { default: config } = await import(__rewriteRelativeImportExtension(pathToFileURL(join(root, 'arcadia.config.mjs')).href));
26
32
  if (!isRecord(config) ||
27
33
  !Array.isArray(config.teams) ||
@@ -29,7 +35,12 @@ export async function prepareContentPack(root = process.cwd(), options = {}) {
29
35
  config.teams.some((id) => typeof id !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,79}$/.test(id)) ||
30
36
  Object.keys(config).some(key => key !== 'teams'))
31
37
  throw new Error('arcadia.config.mjs must export exactly two project team IDs in teams');
32
- const teams = config.teams;
38
+ return config.teams;
39
+ }
40
+ /** Prepare a captured author project with its selected environment and saved teams. */
41
+ export async function prepareContentPack(root = process.cwd(), options = {}) {
42
+ root = resolve(root);
43
+ const teams = await defaultTeamIds(root);
33
44
  const prepared = await prepareBattleEnvironment(root, options);
34
45
  const { environment } = prepared;
35
46
  const environmentRules = validateEnvironmentRules(prepared.effectiveRules);
@@ -41,6 +52,9 @@ export async function prepareContentPack(root = process.cwd(), options = {}) {
41
52
  function defaultPlayers() {
42
53
  return prepared.loadTeams(teams);
43
54
  }
55
+ function assertTeam(team) {
56
+ assertPlayableTeam(environmentRules, team, id => environment.content.getSpecies(id), environment.content.getNature, environment.content.getEnhancement, environment.content.getSkill, environment.content.getMark);
57
+ }
44
58
  function runtimePlayers(supplied, runtimeIds = false) {
45
59
  const players = (supplied ?? defaultPlayers()).map(player => ({
46
60
  ...player,
@@ -50,9 +64,8 @@ export async function prepareContentPack(root = process.cwd(), options = {}) {
50
64
  id: runtimeIds ? randomBytes(16).toString('base64url').slice(0, 21) : pet.id,
51
65
  })),
52
66
  }));
53
- for (const player of players) {
54
- assertPlayableTeam(environmentRules, player.team, id => environment.content.getSpecies(id), environment.content.getNature, environment.content.getEnhancement, environment.content.getSkill, environment.content.getMark);
55
- }
67
+ for (const player of players)
68
+ assertTeam(player.team);
56
69
  return players;
57
70
  }
58
71
  const referenceContent = new WeakMap();
@@ -148,6 +161,7 @@ export async function prepareContentPack(root = process.cwd(), options = {}) {
148
161
  }
149
162
  return {
150
163
  ...prepared,
164
+ assertTeam,
151
165
  createBattle,
152
166
  restoreBattle,
153
167
  contentFor,