@arcadia-eternity/content-sdk 4.13.0 → 4.15.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 (68) 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/lib/presentation.js +12 -2
  39. package/dist/managed-projects.d.ts +5 -1
  40. package/dist/managed-projects.js +3 -3
  41. package/dist/mcp-contracts.d.ts +28 -1
  42. package/dist/mcp-contracts.js +24 -1
  43. package/dist/mcp.js +21 -7
  44. package/dist/official-environment-packages.d.ts +6 -0
  45. package/dist/official-environment-packages.js +19 -0
  46. package/dist/official-environments.d.ts +7 -0
  47. package/dist/official-environments.js +25 -0
  48. package/dist/pack-project.d.ts +1 -0
  49. package/dist/pack-project.js +66 -0
  50. package/dist/package-updates.d.ts +2 -1
  51. package/dist/package-updates.js +30 -17
  52. package/dist/prepared-document.d.ts +1 -0
  53. package/dist/prepared-document.js +5 -13
  54. package/dist/preview-control.js +24 -1
  55. package/dist/preview.d.ts +1 -0
  56. package/dist/preview.js +6 -4
  57. package/dist/project.d.ts +1 -0
  58. package/dist/project.js +57 -18
  59. package/dist/template/README.md +8 -8
  60. package/dist/template/package.json +2 -2
  61. package/dist/template/skills/arcadia-content-authoring/SKILL.md +15 -2
  62. package/dist/template/skills/arcadia-content-authoring/references/tool-workflows.md +25 -1
  63. package/dist/testing.d.ts +3 -4
  64. package/dist/testing.js +22 -8
  65. package/dist/workspace-cli.js +6 -4
  66. package/dist/workspace.d.ts +1 -0
  67. package/dist/workspace.js +66 -15
  68. package/package.json +10 -5
package/dist/jobs.js CHANGED
@@ -8,6 +8,7 @@ import { fileURLToPath } from 'node:url';
8
8
  import { tmpdir } from 'node:os';
9
9
  import { AuthorWorkspace, WorkspaceError, diagnostic } from './workspace.js';
10
10
  import { JobJournal } from './job-journal.js';
11
+ import { DebugEnvironments } from './debug-environments.js';
11
12
  import { siblingModulePath } from './module-path.js';
12
13
  const cli = siblingModulePath('cli');
13
14
  const terminal = new Set(['succeeded', 'failed', 'cancelled', 'interrupted']);
@@ -40,7 +41,10 @@ function resultSummary(result) {
40
41
  'integrity',
41
42
  'shasum',
42
43
  'winner',
44
+ 'status',
45
+ 'actions',
43
46
  'turns',
47
+ 'seed',
44
48
  'environmentRevision',
45
49
  'packageName',
46
50
  ])
@@ -99,7 +103,7 @@ export class AuthorJobs {
99
103
  constructor(workspace, { execute = false, env = process.env, executable = process.execPath, } = {}) {
100
104
  this.workspace = workspace;
101
105
  this.execute = execute;
102
- this.env = Object.fromEntries(Object.entries(env).filter(([key]) => /^(PATH|HOME|USERPROFILE|SystemRoot|WINDIR|TEMP|TMP|TMPDIR|LANG|LC_ALL|ARCADIA_NPM_CLI|ARCADIA_PREVIEW_CLIENT_URL|npm_config_cache)$/i.test(key)));
106
+ this.env = Object.fromEntries(Object.entries(env).filter(([key]) => /^(PATH|HOME|USERPROFILE|SystemRoot|WINDIR|TEMP|TMP|TMPDIR|LANG|LC_ALL|ARCADIA_NPM_CLI|ARCADIA_PREVIEW_CLIENT_URL|npm_config_cache|npm_config_offline)$/i.test(key)));
103
107
  this.executable = executable;
104
108
  this.#changed = ({ file } = {}) => {
105
109
  for (const { job } of this.#jobs.values())
@@ -165,6 +169,11 @@ export class AuthorJobs {
165
169
  return false;
166
170
  }
167
171
  }
172
+ async #isStale(job, revision, contentRevision) {
173
+ if (job.kind === 'preview')
174
+ return job.contentRevision !== contentRevision || !(await this.#dependenciesCurrent(job));
175
+ return job.sourceRevision !== revision || (job.kind === 'demo' && !(await this.#dependenciesCurrent(job)));
176
+ }
168
177
  async refresh() {
169
178
  await this.#checkpoint();
170
179
  if (!this.#journal)
@@ -173,10 +182,7 @@ export class AuthorJobs {
173
182
  const contentRevision = await this.workspace.revision({ contentOnly: true });
174
183
  for (const { job } of this.#jobs.values())
175
184
  if (terminal.has(job.state))
176
- job.stale ||=
177
- job.kind === 'preview'
178
- ? job.contentRevision !== contentRevision || !(await this.#dependenciesCurrent(job))
179
- : job.sourceRevision !== revision;
185
+ job.stale ||= await this.#isStale(job, revision, contentRevision);
180
186
  await this.#refreshReceipts({ revision, contentRevision });
181
187
  }
182
188
  async #refreshReceipts(revisions) {
@@ -192,21 +198,22 @@ export class AuthorJobs {
192
198
  continue;
193
199
  receipt.job.stale ||= this.#jobs.get(receipt.job.jobId)?.job.stale ?? false;
194
200
  if (revisions)
195
- receipt.job.stale ||=
196
- receipt.job.kind === 'preview'
197
- ? receipt.job.contentRevision !== revisions.contentRevision ||
198
- !(await this.#dependenciesCurrent(receipt.job))
199
- : receipt.job.sourceRevision !== revisions.revision;
201
+ receipt.job.stale ||= await this.#isStale(receipt.job, revisions.revision, revisions.contentRevision);
200
202
  this.#jobs.set(receipt.job.jobId, { job: receipt.job, live: receipt.live });
201
203
  }
202
204
  }
203
- async start({ kind, sourceRevision, environmentId = 'default', }) {
205
+ async start({ kind, sourceRevision, environmentId = 'default', seed, }) {
204
206
  if (this.workspace.assertWritable)
205
207
  await this.workspace.assertWritable();
206
208
  if (this.#closed)
207
209
  throw new WorkspaceError('WORKSPACE_CLOSED', '任务宿主已关闭');
208
210
  if (!['check', 'test', 'demo', 'preview', 'pack', 'release'].includes(kind))
209
211
  throw new WorkspaceError('TASK_INVALID', '不支持的作者任务');
212
+ const standalone = this.workspace.projectKind === 'environment';
213
+ if (standalone && kind === 'release')
214
+ throw new WorkspaceError('TASK_INVALID', '此发行检查需要内容包源项目');
215
+ if (seed !== undefined && (kind !== 'demo' || typeof seed !== 'string' || !seed.length || seed.length > 200))
216
+ throw new WorkspaceError('TASK_INVALID', '演示对战的随机种子需要 1–200 个字符');
210
217
  if (kind !== 'check' && !this.execute)
211
218
  throw new WorkspaceError('EXECUTION_DISABLED', '此会话未启用项目代码执行');
212
219
  if (this.#active)
@@ -224,6 +231,12 @@ export class AuthorJobs {
224
231
  });
225
232
  try {
226
233
  const revision = await this.workspace.revision();
234
+ if (standalone) {
235
+ const [environment] = await new DebugEnvironments(this.workspace).list();
236
+ if (environmentId !== 'default' && environmentId !== environment.id)
237
+ throw new WorkspaceError('ENVIRONMENT_MISSING', '此项目没有指定环境:' + environmentId);
238
+ environmentId = environment.id;
239
+ }
227
240
  if (this.#closed)
228
241
  throw new WorkspaceError('WORKSPACE_CLOSED', '任务宿主已关闭');
229
242
  if (sourceRevision && sourceRevision !== revision)
@@ -234,6 +247,7 @@ export class AuthorJobs {
234
247
  sourceRevision: revision,
235
248
  contentRevision: await this.workspace.revision({ contentOnly: true }),
236
249
  environmentId,
250
+ ...(seed !== undefined && { seed }),
237
251
  preparationRevision: await this.workspace.revision({
238
252
  contentOnly: true,
239
253
  excludeFile: environmentId === 'default' ? undefined : `debug/environments/${environmentId}.package-lock.json`,
@@ -407,7 +421,8 @@ export class AuthorJobs {
407
421
  await mkdir(dirname(target), { recursive: true });
408
422
  await cp(await this.workspace.path(entry.file), target);
409
423
  }
410
- await symlink(join(this.workspace.root, 'node_modules'), join(capture, 'node_modules'), process.platform === 'win32' ? 'junction' : 'dir');
424
+ if (this.workspace.projectKind !== 'environment')
425
+ await symlink(join(this.workspace.root, 'node_modules'), join(capture, 'node_modules'), process.platform === 'win32' ? 'junction' : 'dir');
411
426
  if ((await this.workspace.revision({ contentOnly: true })) !== job.contentRevision)
412
427
  throw new WorkspaceError('PREVIEW_STALE', '复制候选期间源码已改变,请重试');
413
428
  }
@@ -423,7 +438,7 @@ export class AuthorJobs {
423
438
  else {
424
439
  if (job.kind === 'release')
425
440
  await this.#process([cli, 'pack', '--release'], job, signal);
426
- else
441
+ else if (this.workspace.projectKind !== 'environment')
427
442
  await this.#process([cli, 'build'], job, signal, false, capture);
428
443
  if (job.kind === 'demo' || job.kind === 'preview')
429
444
  await this.#process([cli, job.kind], job, signal, job.kind === 'preview', capture);
@@ -481,7 +496,8 @@ export class AuthorJobs {
481
496
  job.kind === 'preview'
482
497
  ? (await this.workspace.revision({ contentOnly: true })) !== job.contentRevision ||
483
498
  !(await this.#dependenciesCurrent(job))
484
- : (await this.workspace.revision()) !== job.sourceRevision;
499
+ : (await this.workspace.revision()) !== job.sourceRevision ||
500
+ (job.kind === 'demo' && !(await this.#dependenciesCurrent(job)));
485
501
  if (job.stale && job.kind === 'preview') {
486
502
  controller.abort();
487
503
  state = 'failed';
@@ -528,7 +544,10 @@ export class AuthorJobs {
528
544
  ARCADIA_TEST_RELEASE_INTEGRITY: release.integrity,
529
545
  }
530
546
  : {}),
531
- ...(preview ? { ARCADIA_DEBUG_ENVIRONMENT: job.environmentId, ARCADIA_DEBUG_ROOT: this.workspace.root } : {}),
547
+ ...(preview || job.kind === 'demo'
548
+ ? { ARCADIA_DEBUG_ENVIRONMENT: job.environmentId, ARCADIA_DEBUG_ROOT: this.workspace.root }
549
+ : {}),
550
+ ...(job.seed !== undefined && { ARCADIA_DEBUG_SEED: job.seed }),
532
551
  },
533
552
  stdio: ['ignore', 'pipe', 'pipe', ...(preview ? ['ipc'] : [])],
534
553
  windowsHide: true,
@@ -121,12 +121,15 @@ export async function buildPresentation(root, sources, { includeLocales = true }
121
121
  typeof kind !== 'string' ||
122
122
  !['image', 'audio', 'swf'].includes(kind) ||
123
123
  typeof location !== 'string' ||
124
- Object.keys(record).some(key => !['id', 'source', 'kind', 'name', 'tags'].includes(key)) ||
124
+ Object.keys(record).some(key => !['id', 'source', 'kind', 'name', 'tags', 'sha256'].includes(key)) ||
125
125
  (record.name !== undefined && typeof record.name !== 'string') ||
126
126
  (record.tags !== undefined &&
127
127
  (!Array.isArray(record.tags) || record.tags.some((tag) => typeof tag !== 'string'))))
128
128
  throw new Error(`${relative(root, source.file)}: Invalid resource definition ${id}`);
129
129
  const url = remote(location) ? new URL(location) : undefined;
130
+ if (record.sha256 !== undefined &&
131
+ (!url || typeof record.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(record.sha256)))
132
+ throw new Error(`Invalid HTTP resource SHA-256: ${id}`);
130
133
  if (url && (url.username || url.password))
131
134
  throw new Error(`Resource URL must not contain credentials: ${id}`);
132
135
  const mime = mimeTypes[extname(url ? url.pathname : location).toLowerCase()];
@@ -138,7 +141,14 @@ export async function buildPresentation(root, sources, { includeLocales = true }
138
141
  : mime !== 'application/x-shockwave-flash'))
139
142
  throw new Error(`Resource type does not match source: ${id}`);
140
143
  if (url) {
141
- resources.push({ kind: 'http', id, source: location, mime, ...(record.tags ? { tags: record.tags } : {}) });
144
+ resources.push({
145
+ kind: 'http',
146
+ id,
147
+ source: location,
148
+ mime,
149
+ ...(typeof record.sha256 === 'string' && { sha256: record.sha256 }),
150
+ ...(record.tags ? { tags: record.tags } : {}),
151
+ });
142
152
  continue;
143
153
  }
144
154
  if (!validAssetPath(location))
@@ -1,3 +1,4 @@
1
+ import type { OfficialEnvironmentCatalog } from './official-environments.js';
1
2
  import { type PackageUpdate } from './package-updates.js';
2
3
  export { officialPackage, findPackageUpdate, selectPackageUpdate, startAutomaticContentUpdates, selectServerBase, installServerBaseUpdate, } from './package-updates.js';
3
4
  import type { ContentWorkspace, EnvironmentInstallation, PrepareEnvironmentInput, StaticPreparer } from './content-workspace.js';
@@ -17,6 +18,9 @@ export interface ManagedProjectsOptions {
17
18
  maxFiles?: number;
18
19
  maxConcurrent?: number;
19
20
  }
21
+ export declare function checkLock(lock: unknown, candidates?: boolean): void;
22
+ /** No inherited npm configuration, loader hooks, or author script can alter install behavior. */
23
+ export declare function installationEnvironment(cache: string, configuration: string): Record<string, string>;
20
24
  /**
21
25
  * Resolves a captured draft into a standard installed npm project. Construction and
22
26
  * source registration belong to the host, while requests contain only environment IDs.
@@ -51,4 +55,4 @@ export declare class ManagedProjects {
51
55
  }, consume: (directory: string, signal: AbortSignal) => Promise<T>): Promise<T>;
52
56
  close(): Promise<void>;
53
57
  }
54
- export declare function withOfficialUpdateArchive<T>(candidate: PackageUpdate, npmCli: string | undefined, signal: AbortSignal, use: (file: string) => Promise<T>): Promise<T>;
58
+ export declare function withOfficialUpdateArchive<T>(candidate: PackageUpdate, npmCli: string | undefined, signal: AbortSignal, use: (file: string, catalog: OfficialEnvironmentCatalog) => Promise<T>): Promise<T>;
@@ -44,7 +44,7 @@ function checkDependencySpecs(manifest) {
44
44
  }
45
45
  }
46
46
  }
47
- function checkLock(lock, candidates = false) {
47
+ export function checkLock(lock, candidates = false) {
48
48
  if (!isRecord(lock) || lock.lockfileVersion !== 3 || !isRecord(lock.packages))
49
49
  throw contentError('INSTALL_LOCK_INVALID');
50
50
  for (const [location, value] of Object.entries(lock.packages)) {
@@ -64,7 +64,7 @@ function checkLock(lock, candidates = false) {
64
64
  }
65
65
  }
66
66
  /** No inherited npm configuration, loader hooks, or author script can alter install behavior. */
67
- function installationEnvironment(cache, configuration) {
67
+ export function installationEnvironment(cache, configuration) {
68
68
  const result = {};
69
69
  for (const key of ['PATH', 'Path', 'SystemRoot', 'WINDIR', 'TEMP', 'TMP', 'TMPDIR', 'HOME', 'USERPROFILE', 'LANG'])
70
70
  if (process.env[key])
@@ -608,5 +608,5 @@ export class ManagedProjects {
608
608
  // Discard the npm development/runtime dependencies before passing the official catalog
609
609
  // to the same offline installer used for the application's bundled copy.
610
610
  export async function withOfficialUpdateArchive(candidate, npmCli, signal, use) {
611
- return withOfficialUpdateDirectory(candidate, signal, directory => withShippedCatalogArchive(directory, npmCli, use));
611
+ return withOfficialUpdateDirectory(candidate, signal, (directory, catalog) => withShippedCatalogArchive(directory, npmCli, file => use(file, catalog)));
612
612
  }
@@ -61,7 +61,7 @@ export declare const outputSchemas: {
61
61
  project: "project";
62
62
  }>;
63
63
  readOnly: z.ZodBoolean;
64
- namespace: z.ZodString;
64
+ namespace: z.ZodOptional<z.ZodString>;
65
65
  packageName: z.ZodOptional<z.ZodString>;
66
66
  id: z.ZodOptional<z.ZodString>;
67
67
  qualifiedId: z.ZodOptional<z.ZodString>;
@@ -297,6 +297,17 @@ export declare const outputSchemas: {
297
297
  version: z.ZodString;
298
298
  }, z.core.$strip>>;
299
299
  }, z.core.$strip>;
300
+ 'team-validate': z.ZodObject<{
301
+ teamId: z.ZodString;
302
+ teamVersion: z.ZodString;
303
+ environmentId: z.ZodString;
304
+ environmentRevision: z.ZodString;
305
+ valid: z.ZodBoolean;
306
+ diagnostic: z.ZodOptional<z.ZodObject<{
307
+ code: z.ZodString;
308
+ message: z.ZodString;
309
+ }, z.core.$strip>>;
310
+ }, z.core.$strip>;
300
311
  'team-save': z.ZodObject<{
301
312
  schemaVersion: z.ZodLiteral<1>;
302
313
  id: z.ZodString;
@@ -700,6 +711,22 @@ export declare const outputSchemas: {
700
711
  }, z.core.$strict>;
701
712
  version: z.ZodNullable<z.ZodString>;
702
713
  }, z.core.$strict>], "schemaVersion">;
714
+ 'dependency-install': z.ZodObject<{
715
+ directory: z.ZodString;
716
+ manifestVersion: z.ZodString;
717
+ installationDigest: z.ZodString;
718
+ packages: z.ZodArray<z.ZodObject<{
719
+ name: z.ZodString;
720
+ version: z.ZodString;
721
+ }, z.core.$strip>>;
722
+ }, z.core.$strip>;
723
+ 'environment-install': z.ZodObject<{
724
+ directory: z.ZodString;
725
+ id: z.ZodString;
726
+ name: z.ZodString;
727
+ version: z.ZodString;
728
+ integrity: z.ZodString;
729
+ }, z.core.$loose>;
703
730
  reference: z.ZodObject<{
704
731
  topic: z.ZodString;
705
732
  title: z.ZodString;
@@ -84,7 +84,7 @@ export const outputSchemas = {
84
84
  kind: z.string(),
85
85
  scope: z.enum(['project', 'dependencies']),
86
86
  readOnly: z.boolean(),
87
- namespace: z.string(),
87
+ namespace: z.string().optional(),
88
88
  packageName: z.string().optional(),
89
89
  id: z.string().optional(),
90
90
  qualifiedId: z.string().optional(),
@@ -121,10 +121,33 @@ export const outputSchemas = {
121
121
  unit: z.literal('utf16'),
122
122
  }),
123
123
  'team-list': z.object({ items: z.array(team) }),
124
+ 'team-validate': z.object({
125
+ teamId: identifier,
126
+ teamVersion: version,
127
+ environmentId: identifier,
128
+ environmentRevision: z.string(),
129
+ valid: z.boolean(),
130
+ diagnostic: z.object({ code: z.string(), message: z.string() }).optional(),
131
+ }),
124
132
  'team-save': team,
125
133
  'team-remove': z.object({ id: identifier, removed: z.literal(true) }),
126
134
  'environment-list': z.object({ items: z.array(environment) }),
127
135
  'environment-save': environment,
136
+ 'dependency-install': z.object({
137
+ directory: z.string(),
138
+ manifestVersion: version,
139
+ installationDigest: z.string(),
140
+ packages: z.array(z.object({ name: z.string(), version: z.string() })),
141
+ }),
142
+ 'environment-install': z
143
+ .object({
144
+ directory: z.string(),
145
+ id: identifier,
146
+ name: z.string(),
147
+ version: z.string(),
148
+ integrity: z.string(),
149
+ })
150
+ .passthrough(),
128
151
  reference: z.object({ topic: z.string(), title: z.string() }).passthrough(),
129
152
  'asset-inspect': z.object({ metadata: record }),
130
153
  battle: z
package/dist/mcp.js CHANGED
@@ -31,15 +31,16 @@ const session = await openAuthorSession(directory, {
31
31
  published: options.has('--published'),
32
32
  });
33
33
  const server = new McpServer({ name: 'arcadia-content-authoring', version: '0.1.0' });
34
+ const standaloneEnvironment = session.workspace.projectKind === 'environment';
34
35
  function tool(name, description, inputSchema, operation, transform = input => input, readOnly = false) {
35
36
  server.registerTool(name, {
36
37
  description,
37
38
  inputSchema,
38
39
  outputSchema: { result: outputSchemas[operation] },
39
40
  annotations: { readOnlyHint: readOnly, ...(readOnly ? { destructiveHint: false, idempotentHint: true } : {}) },
40
- }, async (input) => {
41
+ }, async (input, extra) => {
41
42
  try {
42
- const value = await session.call(operation, transform(input));
43
+ const value = await session.call(operation, transform(input), extra.signal);
43
44
  let result = value;
44
45
  let image;
45
46
  if (operation === 'asset-inspect' && isRecord(value)) {
@@ -111,7 +112,7 @@ if (!session.workspace.readOnly)
111
112
  .nullable(),
112
113
  text: z.string().max(2 * 1024 * 1024),
113
114
  }, 'write');
114
- if (!session.workspace.readOnly)
115
+ if (!session.workspace.readOnly && !standaloneEnvironment)
115
116
  tool('content_apply', 'Save reviewed records or name/description entries. create-record uses a new data file and expectedVersion:null; new locale files also use null. Query sources first. Keeps YAML sharing read-only, checks versions and groups edits per file. Inspect complete and every result; partial writes are not rolled back.', {
116
117
  changes: z
117
118
  .array(z.object({
@@ -131,18 +132,22 @@ if (!session.workspace.readOnly)
131
132
  for (const [name, kind] of [
132
133
  ['check_start', 'check'],
133
134
  ['test_start', 'test'],
135
+ ['demo_start', 'demo'],
134
136
  ['preview_start', 'preview'],
135
137
  ['package_build', 'pack'],
136
138
  ['release_check', 'release'],
137
139
  ]) {
138
140
  if (session.workspace.readOnly)
139
141
  continue;
142
+ if (standaloneEnvironment && kind === 'release')
143
+ continue;
140
144
  if (kind !== 'check' && !options.has('--execute'))
141
145
  continue;
142
146
  tool(name, kind === 'preview'
143
- ? 'Build and install a captured npm candidate, then keep a local Node battle host ready for the full client. Poll job_get for preview.url or preview.clientPath. job_cancel stops it; new candidates do not replace existing battles.'
147
+ ? 'Prepare the bound environment or content pack, then start a local battle host for interactive and automated battles. Poll job_get for the candidate and preview endpoint.'
144
148
  : `Start ${kind}; poll job_get for actual output and stale-source state.`, {
145
- ...(kind === 'preview'
149
+ ...(kind === 'demo' ? { seed: z.string().min(1).max(200).optional() } : {}),
150
+ ...(kind === 'preview' || kind === 'demo'
146
151
  ? {
147
152
  environmentId: z
148
153
  .string()
@@ -176,8 +181,17 @@ tool('job_output', 'Read an incremental log chunk using UTF-16 code-unit cursors
176
181
  }, 'job-output', undefined, true);
177
182
  tool('job_cancel', 'Cancel a task and terminate its child process group; source files are retained.', { jobId: z.string() }, 'cancel-query');
178
183
  tool('team_list', 'Read saved project test teams and versions. These are not the user’s unsaved team drafts or current battle players.', {}, 'team-list', undefined, true);
179
- tool('environment_list', 'Read saved named battle environments and versions. Reading or saving an environment does not select it in the desktop.', {}, 'environment-list', undefined, true);
184
+ tool('environment_list', 'Read the bound environment declaration and its version, or the named debug environments of a content pack.', {}, 'environment-list', undefined, true);
180
185
  if (!session.workspace.readOnly) {
186
+ tool('dependency_install', 'Install the bound project’s declared content dependencies into a persistent local npm installation. Read package.json first for its version. Installed content remains available after reconnecting.', { expectedVersion: version, offline: z.boolean().optional() }, 'dependency-install');
187
+ tool('environment_install', 'Install an environment from an exact npm version or an archive in the bound project. The returned directory can be opened as an independent author project by the client or by a new MCP session.', {
188
+ source: z.discriminatedUnion('kind', [
189
+ z.object({ kind: z.literal('npm'), name: z.string().min(1).max(214), version: z.string().min(1).max(256) }),
190
+ z.object({ kind: z.literal('archive'), file: z.string().min(1).max(1000) }),
191
+ ]),
192
+ offline: z.boolean().optional(),
193
+ }, 'environment-install');
194
+ tool('team_validate', 'Check one saved team against an active preview’s frozen environment rules. Returns the team version, environment revision and the first admission failure. Does not create or change a battle.', { jobId: z.string(), teamId: identifier }, 'team-validate', undefined, true);
181
195
  tool('team_save', 'Save a project team against its file version; null creates a new team. Does not overwrite desktop drafts, change selections or replace a running match. Conflicting user drafts remain available for reconciliation.', {
182
196
  document: TeamDocumentSchema,
183
197
  expectedVersion: version.nullable(),
@@ -186,7 +200,7 @@ if (!session.workspace.readOnly) {
186
200
  id: identifier,
187
201
  expectedVersion: version,
188
202
  }, 'team-remove');
189
- tool('environment_save', 'Save a named environment against its version; null creates it. Does not install dependencies or change the user’s selected environment. Prepare a new preview to use the changed configuration.', {
203
+ tool('environment_save', 'Save the standalone environment declaration against its manifest version. In a content pack, save a named debug environment (null creates one). Start a new preview to use changed rules.', {
190
204
  document: EnvironmentDocumentSchema,
191
205
  expectedVersion: version.nullable(),
192
206
  }, 'environment-save');
@@ -0,0 +1,6 @@
1
+ export declare const officialBasePackage = "@arcadia-eternity/data-pack-base";
2
+ export declare const officialEnvironmentPackages: {
3
+ 'builtin-server': string;
4
+ 'training-120': string;
5
+ };
6
+ export declare function resolveOfficialWorkspaceManifest(manifest: unknown): unknown;
@@ -0,0 +1,19 @@
1
+ import { valid } from 'semver';
2
+ import { isRecord } from './types.js';
3
+ export const officialBasePackage = '@arcadia-eternity/data-pack-base';
4
+ export const officialEnvironmentPackages = {
5
+ 'builtin-server': '@arcadia-eternity/environment-default',
6
+ 'training-120': '@arcadia-eternity/environment-training-120',
7
+ };
8
+ // These recipes and the base package share a release version. pnpm pins workspace:* to it when packing.
9
+ export function resolveOfficialWorkspaceManifest(manifest) {
10
+ if (!isRecord(manifest) ||
11
+ typeof manifest.name !== 'string' ||
12
+ !Object.values(officialEnvironmentPackages).includes(manifest.name) ||
13
+ typeof manifest.version !== 'string' ||
14
+ !valid(manifest.version) ||
15
+ !isRecord(manifest.dependencies) ||
16
+ manifest.dependencies[officialBasePackage] !== 'workspace:*')
17
+ return manifest;
18
+ return { ...manifest, dependencies: { ...manifest.dependencies, [officialBasePackage]: manifest.version } };
19
+ }
@@ -0,0 +1,7 @@
1
+ import { type EnvironmentDocumentV2 } from './debug-environments.js';
2
+ export type OfficialEnvironmentCatalog = {
3
+ defaultEnvironment: string;
4
+ environments: EnvironmentDocumentV2[];
5
+ };
6
+ export declare function officialEnvironmentCatalog(baseVersion: string, read: (name: string) => Promise<unknown>): Promise<OfficialEnvironmentCatalog>;
7
+ export declare function bundledEnvironmentCatalog(baseVersion: string, resolve: (specifier: string) => string): Promise<OfficialEnvironmentCatalog>;
@@ -0,0 +1,25 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { environmentManifestDocument } from './debug-environments.js';
3
+ import { officialBasePackage, officialEnvironmentPackages, resolveOfficialWorkspaceManifest, } from './official-environment-packages.js';
4
+ import { isRecord } from './types.js';
5
+ export async function officialEnvironmentCatalog(baseVersion, read) {
6
+ const environments = await Promise.all(Object.entries(officialEnvironmentPackages).map(async ([id, name]) => {
7
+ const manifest = await read(name);
8
+ if (!isRecord(manifest) || manifest.name !== name || manifest.version !== baseVersion)
9
+ throw new Error('OFFICIAL_ENVIRONMENT_PACKAGE_MISMATCH: ' + name);
10
+ const document = environmentManifestDocument(manifest);
11
+ if (document.id !== id ||
12
+ document.sources.length ||
13
+ Object.keys(document.packages).length !== 1 ||
14
+ document.packages[officialBasePackage] !== baseVersion)
15
+ throw new Error('OFFICIAL_ENVIRONMENT_PACKAGE_MISMATCH: ' + name);
16
+ return document;
17
+ }));
18
+ return { defaultEnvironment: 'builtin-server', environments };
19
+ }
20
+ export function bundledEnvironmentCatalog(baseVersion, resolve) {
21
+ return officialEnvironmentCatalog(baseVersion, async (name) => {
22
+ const manifest = JSON.parse(await readFile(resolve(name + '/package.json'), 'utf8'));
23
+ return resolveOfficialWorkspaceManifest(manifest);
24
+ });
25
+ }
@@ -1,3 +1,4 @@
1
+ export declare function packEnvironmentProject(directory: string): Promise<import("@arcadia-eternity/pack-loader/node").NpmPackEntry>;
1
2
  /** Trusted author packaging: close the effect dependency graph without evaluating it.
2
3
  * Only the staged package gains artifact metadata; the source manifest is never rewritten.
3
4
  */
@@ -4,6 +4,10 @@ import { copyFile, lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, writeF
4
4
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
5
5
  import { promisify } from 'node:util';
6
6
  import { compileEffectModule, emptyNpmContentHost, parseNpmPackOutput, prepareNpmProject, resolveNpmInvocation, } from '@arcadia-eternity/pack-loader/node';
7
+ import { AuthorWorkspace } from './workspace.js';
8
+ import { ProjectTeams } from './project-teams.js';
9
+ import { environmentProjectDocument } from './debug-environments.js';
10
+ import { assertEnvironmentRequirements, prepareEnvironmentRules } from './environment-rules.js';
7
11
  import { releasePayload, normalizeReleaseArchive, requireClientRange } from '../release-payload.mjs';
8
12
  import { ManagedProjects } from './managed-projects.js';
9
13
  import { errorCode } from './types.js';
@@ -82,6 +86,68 @@ async function verifyRelease(directory, archive, name) {
82
86
  await installer.close();
83
87
  }
84
88
  }
89
+ // Environment archives carry the declarative recipe and its portable inputs.
90
+ export async function packEnvironmentProject(directory) {
91
+ const workspace = await AuthorWorkspace.open(directory, { watch: false });
92
+ let temporary;
93
+ try {
94
+ await workspace.assertWritable();
95
+ const manifestSource = await workspace.read('package.json');
96
+ const manifest = JSON.parse(manifestSource.text);
97
+ const document = environmentProjectDocument(manifest);
98
+ assertEnvironmentRequirements(document.requires);
99
+ prepareEnvironmentRules(document.rules);
100
+ if (document.sources.length)
101
+ throw new Error('请先把本机源码依赖打包,改用已发布版本或 file:candidates/*.tgz 后再分发环境。');
102
+ const { packages: dependencies, ...arcadiaEnvironment } = document;
103
+ const teamLibrary = new ProjectTeams(workspace);
104
+ const teams = await teamLibrary.list();
105
+ const files = new Set(teams.map(team => teamLibrary.file(team.id)));
106
+ for (const spec of Object.values(dependencies)) {
107
+ if (spec.startsWith('file:'))
108
+ files.add(spec.slice(5));
109
+ }
110
+ temporary = await mkdtemp(join(await stagingRoot(workspace.root), 'environment-'));
111
+ const payload = join(temporary, 'package');
112
+ await mkdir(payload);
113
+ const captured = new Map();
114
+ for (const file of files) {
115
+ const source = await sourceFile(workspace.root, file);
116
+ captured.set(source.path, source);
117
+ const target = join(payload, file);
118
+ await mkdir(dirname(target), { recursive: true });
119
+ await copyFile(source.path, target);
120
+ }
121
+ const recipe = {
122
+ name: manifest.name,
123
+ version: manifest.version,
124
+ description: manifest.description,
125
+ license: manifest.license,
126
+ engines: manifest.engines,
127
+ private: manifest.private,
128
+ files: [...files],
129
+ dependencies,
130
+ arcadiaEnvironment,
131
+ };
132
+ await writeFile(join(payload, 'package.json'), JSON.stringify(recipe, null, 2) + '\n');
133
+ const packed = parseNpmPackOutput(String((await npm(payload, ['pack', '--offline', '--ignore-scripts', '--json', '--pack-destination', temporary], process.env.npm_config_cache ?? join(temporary, 'cache'))).stdout))[0];
134
+ if (!packed || !packed.shasum || basename(packagePath(packed.filename)) !== packed.filename)
135
+ fail('npm returned an invalid environment package receipt');
136
+ const actual = new Set(packed.files.map(file => file.path));
137
+ if (actual.size !== files.size + 1 || !actual.has('package.json') || [...files].some(file => !actual.has(file)))
138
+ fail('Environment archive does not match the declared files');
139
+ await verifyCapture(captured);
140
+ if ((await workspace.read('package.json')).version !== manifestSource.version)
141
+ fail('Environment manifest changed during packaging');
142
+ await rename(join(temporary, packed.filename), join(workspace.root, packed.filename));
143
+ return packed;
144
+ }
145
+ finally {
146
+ if (temporary)
147
+ await rm(temporary, { recursive: true, force: true });
148
+ await workspace.close();
149
+ }
150
+ }
85
151
  /** Trusted author packaging: close the effect dependency graph without evaluating it.
86
152
  * Only the staged package gains artifact metadata; the source manifest is never rewritten.
87
153
  */
@@ -1,3 +1,4 @@
1
+ import { type OfficialEnvironmentCatalog } from './official-environments.js';
1
2
  export declare const officialPackage = "@arcadia-eternity/data-pack-base";
2
3
  export interface PackageUpdate {
3
4
  name: string;
@@ -11,7 +12,7 @@ export declare function startAutomaticContentUpdates(update: (options: {
11
12
  }) => Promise<unknown>, onError: (error: unknown) => void): () => Promise<void> | undefined;
12
13
  export declare function selectPackageUpdate(metadata: unknown, name: string, current: string, client: string): PackageUpdate | null;
13
14
  export declare function findPackageUpdate(name: string, current: string, client: string, signal?: AbortSignal): Promise<PackageUpdate | null>;
14
- export declare function withOfficialUpdateDirectory<T>(candidate: PackageUpdate, signal: AbortSignal, use: (directory: string) => Promise<T>): Promise<T>;
15
+ export declare function withOfficialUpdateDirectory<T>(candidate: PackageUpdate, signal: AbortSignal, use: (directory: string, catalog: OfficialEnvironmentCatalog) => Promise<T>): Promise<T>;
15
16
  /** Only completed version directories are eligible. Offline startup never contacts the registry. */
16
17
  export declare function selectServerBase(store: string, shipped: string, host: string, pin?: string, validate?: (directory: string) => Promise<void>): Promise<{
17
18
  directory: string;