@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.
- package/README.md +16 -5
- package/dist/appimage-sdk.d.ts +2 -0
- package/dist/appimage-sdk.js +110 -0
- package/dist/author-api.d.ts +6 -1
- package/dist/author-api.js +27 -3
- package/dist/author-environment-install.d.ts +14 -0
- package/dist/author-environment-install.js +104 -0
- package/dist/author-environment-source.d.ts +162 -0
- package/dist/author-environment-source.js +226 -0
- package/dist/author-install.d.ts +22 -0
- package/dist/author-install.js +289 -0
- package/dist/author-reference.d.ts +1 -1
- package/dist/author-reference.js +23 -4
- package/dist/cli.js +56 -23
- package/dist/command-discovery.d.ts +3 -0
- package/dist/command-discovery.js +122 -0
- package/dist/content-query.js +4 -1
- package/dist/content-workspace.d.ts +2 -138
- package/dist/content-workspace.js +6 -6
- package/dist/debug-environment-install.d.ts +15 -0
- package/dist/debug-environment-install.js +130 -0
- package/dist/debug-environments.d.ts +135 -0
- package/dist/debug-environments.js +48 -0
- package/dist/demo.js +22 -8
- package/dist/desktop-cli.d.ts +3 -0
- package/dist/desktop-cli.js +72 -0
- package/dist/desktop-client.d.ts +71 -0
- package/dist/desktop-client.js +162 -0
- package/dist/environment-demo.d.ts +8 -0
- package/dist/environment-demo.js +52 -0
- package/dist/environment-rules.js +38 -19
- package/dist/environment.d.ts +12 -8
- package/dist/environment.js +107 -58
- package/dist/init.d.ts +1 -0
- package/dist/init.js +125 -0
- package/dist/jobs.d.ts +3 -1
- package/dist/jobs.js +34 -15
- package/dist/managed-projects.d.ts +7 -3
- package/dist/managed-projects.js +10 -6
- package/dist/mcp-contracts.d.ts +28 -1
- package/dist/mcp-contracts.js +24 -1
- package/dist/mcp.js +21 -7
- package/dist/official-environment-packages.d.ts +6 -0
- package/dist/official-environment-packages.js +19 -0
- package/dist/official-environments.d.ts +7 -0
- package/dist/official-environments.js +25 -0
- package/dist/pack-project.d.ts +1 -0
- package/dist/pack-project.js +66 -0
- package/dist/package-updates.d.ts +10 -3
- package/dist/package-updates.js +71 -21
- package/dist/prepared-document.d.ts +1 -0
- package/dist/prepared-document.js +5 -13
- package/dist/preview-control.js +24 -1
- package/dist/preview.d.ts +1 -0
- package/dist/preview.js +6 -4
- package/dist/project.d.ts +1 -0
- package/dist/project.js +57 -18
- package/dist/template/README.md +8 -8
- package/dist/template/package.json +2 -2
- package/dist/template/skills/arcadia-content-authoring/SKILL.md +15 -2
- package/dist/template/skills/arcadia-content-authoring/references/tool-workflows.md +25 -1
- package/dist/testing.d.ts +3 -4
- package/dist/testing.js +22 -8
- package/dist/workspace-cli.js +6 -4
- package/dist/workspace.d.ts +1 -0
- package/dist/workspace.js +66 -15
- package/package.json +10 -5
|
@@ -389,6 +389,141 @@ export type ListedEnvironment = EnvironmentDocument & {
|
|
|
389
389
|
export declare function environmentDocument(input: unknown): EnvironmentDocument;
|
|
390
390
|
/** Read legacy documents into the shared domain model without rewriting source files. */
|
|
391
391
|
export declare function normalizeEnvironmentDocument(value: unknown): EnvironmentDocumentV2;
|
|
392
|
+
export declare function environmentManifestDocument(manifest: unknown): EnvironmentDocumentV2;
|
|
393
|
+
export declare function environmentProjectDocument(manifest: unknown): {
|
|
394
|
+
id: string;
|
|
395
|
+
name: string;
|
|
396
|
+
packages: Record<string, string>;
|
|
397
|
+
sources: string[];
|
|
398
|
+
schemaVersion: 2;
|
|
399
|
+
rules: {
|
|
400
|
+
schemaVersion: 1 | 2;
|
|
401
|
+
mechanics?: {
|
|
402
|
+
skillSlots?: {
|
|
403
|
+
normalMax: number;
|
|
404
|
+
climaxMax: number;
|
|
405
|
+
climaxMin?: number | undefined;
|
|
406
|
+
} | undefined;
|
|
407
|
+
individualValueDefault?: number | undefined;
|
|
408
|
+
individualValues?: {
|
|
409
|
+
max: number;
|
|
410
|
+
} | undefined;
|
|
411
|
+
allowFaintSwitch?: boolean | undefined;
|
|
412
|
+
timer?: {
|
|
413
|
+
enabled: boolean;
|
|
414
|
+
turnTimeLimit?: number | undefined;
|
|
415
|
+
totalTimeLimit?: number | undefined;
|
|
416
|
+
animationPauseEnabled?: boolean | undefined;
|
|
417
|
+
maxAnimationDuration?: number | undefined;
|
|
418
|
+
} | undefined;
|
|
419
|
+
teamSelection?: {
|
|
420
|
+
enabled: boolean;
|
|
421
|
+
mode?: "FULL_TEAM" | "TEAM_SELECTION" | "VIEW_ONLY" | undefined;
|
|
422
|
+
minTeamSize?: number | undefined;
|
|
423
|
+
maxTeamSize?: number | undefined;
|
|
424
|
+
allowStarterSelection?: boolean | undefined;
|
|
425
|
+
showOpponentTeam?: boolean | undefined;
|
|
426
|
+
teamInfoVisibility?: "BASIC" | "FULL" | "HIDDEN" | undefined;
|
|
427
|
+
timeLimit?: number | undefined;
|
|
428
|
+
} | undefined;
|
|
429
|
+
inheritance?: {
|
|
430
|
+
eligible: "all" | "off" | "species" | string[];
|
|
431
|
+
pool?: {
|
|
432
|
+
mode: "append" | "fallback" | "replace";
|
|
433
|
+
skills: string[];
|
|
434
|
+
} | undefined;
|
|
435
|
+
} | undefined;
|
|
436
|
+
enhancement?: {
|
|
437
|
+
mode: "active" | "forbidden" | "suppressed";
|
|
438
|
+
minLevel?: number | undefined;
|
|
439
|
+
defaultBranches?: string[] | undefined;
|
|
440
|
+
stages?: string[] | undefined;
|
|
441
|
+
species?: string[] | undefined;
|
|
442
|
+
} | undefined;
|
|
443
|
+
secondGenerationNatures?: "all" | "off" | "species" | string[] | undefined;
|
|
444
|
+
} | undefined;
|
|
445
|
+
skillParameters?: {
|
|
446
|
+
profile?: string | undefined;
|
|
447
|
+
groups?: Record<string, number> | undefined;
|
|
448
|
+
overrides?: {
|
|
449
|
+
skill: string;
|
|
450
|
+
useId: string;
|
|
451
|
+
parameter: string;
|
|
452
|
+
value: number;
|
|
453
|
+
}[] | undefined;
|
|
454
|
+
} | undefined;
|
|
455
|
+
matchups?: {
|
|
456
|
+
table?: string | undefined;
|
|
457
|
+
adjustments?: {
|
|
458
|
+
attack: string;
|
|
459
|
+
defense: string;
|
|
460
|
+
multiplier: number;
|
|
461
|
+
}[] | undefined;
|
|
462
|
+
} | undefined;
|
|
463
|
+
learnsetAdjustments?: {
|
|
464
|
+
species: string;
|
|
465
|
+
source: "inherited" | "normal";
|
|
466
|
+
skill: string;
|
|
467
|
+
action: "add" | "remove";
|
|
468
|
+
level?: number | undefined;
|
|
469
|
+
}[] | undefined;
|
|
470
|
+
tier?: "standard" | undefined;
|
|
471
|
+
allow?: {
|
|
472
|
+
species?: string[] | undefined;
|
|
473
|
+
skills?: string[] | undefined;
|
|
474
|
+
marks?: string[] | undefined;
|
|
475
|
+
} | undefined;
|
|
476
|
+
deny?: {
|
|
477
|
+
species?: string[] | undefined;
|
|
478
|
+
skills?: string[] | undefined;
|
|
479
|
+
marks?: string[] | undefined;
|
|
480
|
+
} | undefined;
|
|
481
|
+
team?: {
|
|
482
|
+
minSize?: number | undefined;
|
|
483
|
+
maxSize?: number | undefined;
|
|
484
|
+
uniqueSpecies?: boolean | undefined;
|
|
485
|
+
} | undefined;
|
|
486
|
+
constraints?: ({
|
|
487
|
+
id: string;
|
|
488
|
+
allOf: {
|
|
489
|
+
kind: "mark" | "skill" | "species";
|
|
490
|
+
ids: string[];
|
|
491
|
+
fromCollections?: string[] | undefined;
|
|
492
|
+
}[];
|
|
493
|
+
kind: "ban";
|
|
494
|
+
scope: "pet" | "team";
|
|
495
|
+
exceptWhen?: {
|
|
496
|
+
kind: "mark" | "skill" | "species";
|
|
497
|
+
ids: string[];
|
|
498
|
+
fromCollections?: string[] | undefined;
|
|
499
|
+
}[] | undefined;
|
|
500
|
+
exceptAny?: {
|
|
501
|
+
kind: "mark" | "skill" | "species";
|
|
502
|
+
ids: string[];
|
|
503
|
+
fromCollections?: string[] | undefined;
|
|
504
|
+
}[][] | undefined;
|
|
505
|
+
} | {
|
|
506
|
+
id: string;
|
|
507
|
+
allOf: {
|
|
508
|
+
kind: "mark" | "skill" | "species";
|
|
509
|
+
ids: string[];
|
|
510
|
+
fromCollections?: string[] | undefined;
|
|
511
|
+
}[];
|
|
512
|
+
kind: "memberLimit";
|
|
513
|
+
max: number;
|
|
514
|
+
})[] | undefined;
|
|
515
|
+
collections?: {
|
|
516
|
+
id: string;
|
|
517
|
+
kind: "mark" | "skill" | "species";
|
|
518
|
+
ids: string[];
|
|
519
|
+
}[] | undefined;
|
|
520
|
+
};
|
|
521
|
+
requires: {
|
|
522
|
+
engine?: string | undefined;
|
|
523
|
+
sdk?: string | undefined;
|
|
524
|
+
capabilities?: string[] | undefined;
|
|
525
|
+
};
|
|
526
|
+
};
|
|
392
527
|
export declare class DebugEnvironments {
|
|
393
528
|
workspace: AuthorWorkspace;
|
|
394
529
|
constructor(workspace: AuthorWorkspace);
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { IndependentEnvironmentRulesSchema, EnvironmentRequirementsSchema } from '@arcadia-eternity/const';
|
|
2
2
|
export { EnvironmentRuleDeclarationSchema, EnvironmentRulesSchema, } from '@arcadia-eternity/const';
|
|
3
3
|
import { WorkspaceError } from './workspace.js';
|
|
4
|
+
import { officialBasePackage, resolveOfficialWorkspaceManifest } from './official-environment-packages.js';
|
|
5
|
+
import { isRecord } from './types.js';
|
|
4
6
|
import { z } from 'zod';
|
|
5
7
|
const idPattern = /^[a-z0-9][a-z0-9_-]{0,79}$/;
|
|
6
8
|
const packagePattern = /^(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*$/;
|
|
@@ -60,6 +62,20 @@ export function normalizeEnvironmentDocument(value) {
|
|
|
60
62
|
return document;
|
|
61
63
|
return { ...document, schemaVersion: 2, rules: { schemaVersion: 1 }, requires: {} };
|
|
62
64
|
}
|
|
65
|
+
export function environmentManifestDocument(manifest) {
|
|
66
|
+
if (!isRecord(manifest) || !isRecord(manifest.arcadiaEnvironment) || !isRecord(manifest.dependencies))
|
|
67
|
+
throw new WorkspaceError('ENVIRONMENT_MANIFEST_INVALID', '环境包需要 arcadiaEnvironment 声明和 dependencies', 'package.json');
|
|
68
|
+
const { sources } = manifest.arcadiaEnvironment;
|
|
69
|
+
if (!Array.isArray(sources))
|
|
70
|
+
throw new WorkspaceError('ENVIRONMENT_MANIFEST_INVALID', '环境来源必须是一个数组', 'package.json');
|
|
71
|
+
return normalizeEnvironmentDocument({
|
|
72
|
+
...manifest.arcadiaEnvironment,
|
|
73
|
+
packages: Object.fromEntries(Object.entries(manifest.dependencies).filter(([name]) => !sources.includes(name))),
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
export function environmentProjectDocument(manifest) {
|
|
77
|
+
return environmentManifestDocument(resolveOfficialWorkspaceManifest(manifest));
|
|
78
|
+
}
|
|
63
79
|
export class DebugEnvironments {
|
|
64
80
|
workspace;
|
|
65
81
|
constructor(workspace) {
|
|
@@ -71,6 +87,10 @@ export class DebugEnvironments {
|
|
|
71
87
|
return `debug/environments/${id}.json`;
|
|
72
88
|
}
|
|
73
89
|
async list() {
|
|
90
|
+
if (this.workspace.projectKind === 'environment') {
|
|
91
|
+
const source = await this.workspace.read('package.json');
|
|
92
|
+
return [{ ...environmentProjectDocument(JSON.parse(source.text)), version: source.version }];
|
|
93
|
+
}
|
|
74
94
|
const environments = [
|
|
75
95
|
{ schemaVersion: 1, id: 'default', name: '当前包与正式依赖', packages: {}, sources: [], version: null },
|
|
76
96
|
];
|
|
@@ -86,6 +106,34 @@ export class DebugEnvironments {
|
|
|
86
106
|
}
|
|
87
107
|
async save({ document, expectedVersion, }) {
|
|
88
108
|
const value = environmentDocument(document);
|
|
109
|
+
if (this.workspace.projectKind === 'environment') {
|
|
110
|
+
const source = await this.workspace.read('package.json');
|
|
111
|
+
const manifest = JSON.parse(source.text);
|
|
112
|
+
if (source.version !== expectedVersion)
|
|
113
|
+
throw new WorkspaceError('REVISION_CONFLICT', '环境包声明已改变,请重新读取', source.file);
|
|
114
|
+
const previous = environmentProjectDocument(manifest);
|
|
115
|
+
if (previous.id !== value.id)
|
|
116
|
+
fail('环境标识与当前项目不一致');
|
|
117
|
+
const { packages, ...declaration } = normalizeEnvironmentDocument(value);
|
|
118
|
+
if (declaration.sources.some(name => Object.hasOwn(packages, name)))
|
|
119
|
+
fail('同一包不能同时声明版本和本机来源');
|
|
120
|
+
const dependencies = {
|
|
121
|
+
...packages,
|
|
122
|
+
...Object.fromEntries(declaration.sources
|
|
123
|
+
.filter(name => Object.hasOwn(manifest.dependencies, name))
|
|
124
|
+
.map(name => [name, manifest.dependencies[name]])),
|
|
125
|
+
};
|
|
126
|
+
if (manifest.dependencies[officialBasePackage] === 'workspace:*' &&
|
|
127
|
+
dependencies[officialBasePackage] === previous.packages[officialBasePackage] &&
|
|
128
|
+
Object.hasOwn(packages, officialBasePackage))
|
|
129
|
+
dependencies[officialBasePackage] = 'workspace:*';
|
|
130
|
+
const result = await this.workspace.write({
|
|
131
|
+
file: source.file,
|
|
132
|
+
expectedVersion,
|
|
133
|
+
text: JSON.stringify({ ...manifest, dependencies, arcadiaEnvironment: declaration }, null, 2) + '\n',
|
|
134
|
+
});
|
|
135
|
+
return { ...declaration, packages, version: result.version };
|
|
136
|
+
}
|
|
89
137
|
const result = await this.workspace.write({
|
|
90
138
|
file: this.file(value.id),
|
|
91
139
|
expectedVersion,
|
package/dist/demo.js
CHANGED
|
@@ -1,17 +1,31 @@
|
|
|
1
1
|
import { prepareContentPack, runBattle } from './testing.js';
|
|
2
|
+
import { runEnvironmentDemo } from './environment-demo.js';
|
|
3
|
+
import { readSourceMappings } from './preview.js';
|
|
2
4
|
import { setGlobalLogger } from '@arcadia-eternity/battle/engine';
|
|
3
5
|
setGlobalLogger({ debug() { }, info() { }, warn() { }, error() { } });
|
|
4
|
-
const
|
|
6
|
+
const seed = process.env.ARCADIA_DEBUG_SEED ?? 'content-pack-template';
|
|
7
|
+
const sourceRoot = process.env.ARCADIA_DEBUG_ROOT ?? process.cwd();
|
|
8
|
+
const example = await prepareContentPack(process.cwd(), {
|
|
9
|
+
environmentId: process.env.ARCADIA_DEBUG_ENVIRONMENT,
|
|
10
|
+
sourceRoot,
|
|
11
|
+
sources: await readSourceMappings(sourceRoot),
|
|
12
|
+
});
|
|
5
13
|
try {
|
|
6
14
|
console.log(`Package: ${example.manifest.name}`);
|
|
7
|
-
|
|
15
|
+
if (example.manifest.arcadia)
|
|
16
|
+
console.log(`Namespace: ${example.manifest.arcadia.namespace}`);
|
|
8
17
|
console.log(`Environment: ${example.environment.revision}`);
|
|
9
|
-
const result =
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
18
|
+
const result = example.candidate.kind === 'environment'
|
|
19
|
+
? await runEnvironmentDemo(example, seed)
|
|
20
|
+
: await runBattle(await example.createBattle(seed), battle => {
|
|
21
|
+
const pets = [battle.playerA, battle.playerB].map(player => `${player.name}: HP ${player.activePet.currentHp}, speed ${player.activePet.stat.spe}, marks ${player.activePet.marks.length}`);
|
|
22
|
+
console.log(`Turn ${battle.currentTurn}: ${pets.join(' | ')}`);
|
|
23
|
+
});
|
|
24
|
+
if ('status' in result && result.status !== 'completed')
|
|
25
|
+
console.log(`Stopped at ${result.status} after ${result.turns} turns.`);
|
|
26
|
+
else
|
|
27
|
+
console.log(`Winner: ${result.winner ?? '—'}; finished in ${result.turns} turns.`);
|
|
28
|
+
console.log(`ARCADIA_RESULT=${JSON.stringify({ ...result, seed, sourceRevisions: example.sourceRevisions, candidate: example.candidate, environmentRevision: example.candidate.environmentRevision, packageName: example.manifest.name, files: example.files })}`);
|
|
15
29
|
}
|
|
16
30
|
finally {
|
|
17
31
|
await example.dispose();
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { type DesktopConnectionOptions } from './desktop-client.js';
|
|
2
|
+
export declare function desktopCommand(args: string[], options?: DesktopConnectionOptions): Promise<import("./types.js").UnknownRecord>;
|
|
3
|
+
export declare function desktopCli(args: string[]): Promise<void>;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { lstat } from 'node:fs/promises';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import { desktopHelp as usage } from './command-discovery.js';
|
|
5
|
+
import { connectDesktopInstance, listDesktopInstances } from './desktop-client.js';
|
|
6
|
+
async function installSource(value, kind) {
|
|
7
|
+
// A valid npm prerelease or build tag may itself end in .tgz or .zip.
|
|
8
|
+
const { parseAuthorEnvironmentNpmSpec } = await import('./author-environment-source.js');
|
|
9
|
+
try {
|
|
10
|
+
parseAuthorEnvironmentNpmSpec(value);
|
|
11
|
+
return { kind: 'npm', spec: value };
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
if (!/\.(?:tgz|zip)$/i.test(value))
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
if (kind === 'environment' && /\.zip$/i.test(value))
|
|
18
|
+
throw new Error('Select a .tgz environment archive.');
|
|
19
|
+
const file = resolve(value);
|
|
20
|
+
if (!(await lstat(file)).isFile())
|
|
21
|
+
throw new Error('Select a regular archive file.');
|
|
22
|
+
return { kind: 'archive', file };
|
|
23
|
+
}
|
|
24
|
+
export async function desktopCommand(args, options = {}) {
|
|
25
|
+
const { values, positionals } = parseArgs({
|
|
26
|
+
args,
|
|
27
|
+
allowPositionals: true,
|
|
28
|
+
options: {
|
|
29
|
+
instance: { type: 'string' },
|
|
30
|
+
id: { type: 'string' },
|
|
31
|
+
'allow-download': { type: 'boolean' },
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
const [group, operation, source] = positionals;
|
|
35
|
+
const discovery = group === 'instances' && positionals.length === 1 && Object.keys(values).length === 0;
|
|
36
|
+
const installing = operation === 'install';
|
|
37
|
+
if (!discovery &&
|
|
38
|
+
((group !== 'packages' && group !== 'environments') ||
|
|
39
|
+
(installing ? positionals.length !== 3 : operation !== 'list' || positionals.length !== 2) ||
|
|
40
|
+
(values.id !== undefined &&
|
|
41
|
+
(!installing ||
|
|
42
|
+
group !== 'environments' ||
|
|
43
|
+
!/^[a-z0-9][a-z0-9_-]{0,79}$/.test(values.id) ||
|
|
44
|
+
values.id === 'default')) ||
|
|
45
|
+
(!installing && values['allow-download'])))
|
|
46
|
+
throw new Error(usage);
|
|
47
|
+
if (discovery)
|
|
48
|
+
return { instances: await listDesktopInstances(options) };
|
|
49
|
+
const instance = await connectDesktopInstance(values.instance, options);
|
|
50
|
+
const kind = group === 'packages' ? 'pack' : 'environment';
|
|
51
|
+
if (!installing) {
|
|
52
|
+
const result = await instance.request({ operation: 'list', kind });
|
|
53
|
+
if (!Array.isArray(result[group]))
|
|
54
|
+
throw new Error('The desktop instance returned an invalid library listing.');
|
|
55
|
+
return group === 'packages'
|
|
56
|
+
? { packages: result.packages }
|
|
57
|
+
: { environments: result.environments, selectedEnvironmentId: result.selectedEnvironmentId };
|
|
58
|
+
}
|
|
59
|
+
return instance.request({
|
|
60
|
+
operation: 'install',
|
|
61
|
+
kind,
|
|
62
|
+
source: await installSource(source, kind),
|
|
63
|
+
offline: !values['allow-download'],
|
|
64
|
+
...(values.id && { environmentId: values.id }),
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
export async function desktopCli(args) {
|
|
68
|
+
if (args.length === 0 || args.includes('--help') || args.includes('-h'))
|
|
69
|
+
console.log(usage);
|
|
70
|
+
else
|
|
71
|
+
console.log(JSON.stringify(await desktopCommand(args)));
|
|
72
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
type Instance = {
|
|
2
|
+
id: string;
|
|
3
|
+
label: string;
|
|
4
|
+
pid: number;
|
|
5
|
+
port: number;
|
|
6
|
+
token: string;
|
|
7
|
+
};
|
|
8
|
+
export type DesktopServerConfiguration = {
|
|
9
|
+
name: string;
|
|
10
|
+
scope: 'local' | 'lan' | 'public';
|
|
11
|
+
port: number;
|
|
12
|
+
publicOrigin?: string;
|
|
13
|
+
};
|
|
14
|
+
export type DesktopOperation = {
|
|
15
|
+
operation: 'describe';
|
|
16
|
+
} | {
|
|
17
|
+
operation: 'list';
|
|
18
|
+
kind: 'pack' | 'environment';
|
|
19
|
+
} | {
|
|
20
|
+
operation: 'install';
|
|
21
|
+
kind: 'pack' | 'environment';
|
|
22
|
+
source: {
|
|
23
|
+
kind: 'archive';
|
|
24
|
+
file: string;
|
|
25
|
+
} | {
|
|
26
|
+
kind: 'npm';
|
|
27
|
+
spec: string;
|
|
28
|
+
};
|
|
29
|
+
offline?: boolean;
|
|
30
|
+
environmentId?: string;
|
|
31
|
+
} | {
|
|
32
|
+
operation: 'server';
|
|
33
|
+
action: 'status' | 'restart';
|
|
34
|
+
} | {
|
|
35
|
+
operation: 'server';
|
|
36
|
+
action: 'stop';
|
|
37
|
+
force?: boolean;
|
|
38
|
+
} | {
|
|
39
|
+
operation: 'server';
|
|
40
|
+
action: 'start';
|
|
41
|
+
configuration?: DesktopServerConfiguration;
|
|
42
|
+
} | {
|
|
43
|
+
operation: 'battle-environment-acquire';
|
|
44
|
+
environmentId: string;
|
|
45
|
+
} | {
|
|
46
|
+
operation: 'battle-environment-release';
|
|
47
|
+
leaseId: string;
|
|
48
|
+
};
|
|
49
|
+
type Transport = (instance: Instance, input: DesktopOperation, signal?: AbortSignal) => Promise<{
|
|
50
|
+
status: number;
|
|
51
|
+
payload: unknown;
|
|
52
|
+
}>;
|
|
53
|
+
export interface DesktopConnectionOptions {
|
|
54
|
+
signal?: AbortSignal;
|
|
55
|
+
directory?: string;
|
|
56
|
+
transport?: Transport;
|
|
57
|
+
}
|
|
58
|
+
/** Discover responsive players without exposing their private connection credentials. */
|
|
59
|
+
export declare function listDesktopInstances(options?: DesktopConnectionOptions): Promise<{
|
|
60
|
+
id: string;
|
|
61
|
+
label: string;
|
|
62
|
+
}[]>;
|
|
63
|
+
/** Bind each request to one running player. The captured credential never leaves the client. */
|
|
64
|
+
export declare function connectDesktopInstance(id?: string, options?: DesktopConnectionOptions): Promise<{
|
|
65
|
+
id: string;
|
|
66
|
+
label: string;
|
|
67
|
+
request: (operation: DesktopOperation, { signal }?: {
|
|
68
|
+
signal?: AbortSignal;
|
|
69
|
+
}) => Promise<import("./types.js").UnknownRecord>;
|
|
70
|
+
}>;
|
|
71
|
+
export {};
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { lstat, open, readdir } from 'node:fs/promises';
|
|
3
|
+
import { request as httpRequest } from 'node:http';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { errorCode, isRecord } from './types.js';
|
|
7
|
+
const instanceId = /^[a-f0-9]{32}$/;
|
|
8
|
+
const registryProtocol = 'arcadia.player-library/v1';
|
|
9
|
+
function privateToUser(info) {
|
|
10
|
+
return process.platform === 'win32' || (info.uid === process.getuid?.() && (info.mode & 0o077) === 0);
|
|
11
|
+
}
|
|
12
|
+
async function readInstance(directory, id) {
|
|
13
|
+
const path = join(directory, id + '.json');
|
|
14
|
+
try {
|
|
15
|
+
const info = await lstat(path);
|
|
16
|
+
if (!info.isFile() || !privateToUser(info))
|
|
17
|
+
return;
|
|
18
|
+
const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
19
|
+
try {
|
|
20
|
+
const current = await handle.stat();
|
|
21
|
+
if (!current.isFile() || !privateToUser(current) || current.size > 8192)
|
|
22
|
+
return;
|
|
23
|
+
const data = JSON.parse(await handle.readFile('utf8'));
|
|
24
|
+
if (!isRecord(data) ||
|
|
25
|
+
data.protocol !== registryProtocol ||
|
|
26
|
+
data.id !== id ||
|
|
27
|
+
typeof data.label !== 'string' ||
|
|
28
|
+
!data.label ||
|
|
29
|
+
data.label.length > 512 ||
|
|
30
|
+
typeof data.port !== 'number' ||
|
|
31
|
+
!Number.isInteger(data.port) ||
|
|
32
|
+
data.port < 1 ||
|
|
33
|
+
data.port > 65535 ||
|
|
34
|
+
typeof data.pid !== 'number' ||
|
|
35
|
+
!Number.isSafeInteger(data.pid) ||
|
|
36
|
+
data.pid < 1 ||
|
|
37
|
+
data.pid > 0x7fffffff ||
|
|
38
|
+
typeof data.token !== 'string' ||
|
|
39
|
+
!/^[a-f0-9]{64}$/.test(data.token))
|
|
40
|
+
return;
|
|
41
|
+
try {
|
|
42
|
+
process.kill(data.pid, 0);
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
if (errorCode(error) !== 'EPERM')
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
return { id, label: data.label, port: data.port, pid: data.pid, token: data.token };
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
await handle.close();
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (error instanceof SyntaxError ||
|
|
56
|
+
['ENOENT', 'ELOOP', 'ESRCH', 'EPERM', 'EACCES'].includes(errorCode(error) ?? ''))
|
|
57
|
+
return;
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
async function postToOwner(instance, input, signal) {
|
|
62
|
+
const timeout = {
|
|
63
|
+
describe: 2500,
|
|
64
|
+
list: 30_000,
|
|
65
|
+
install: 15 * 60_000,
|
|
66
|
+
server: input.operation === 'server' && input.action === 'status' ? 30_000 : undefined,
|
|
67
|
+
'battle-environment-acquire': 120_000,
|
|
68
|
+
'battle-environment-release': 10_000,
|
|
69
|
+
}[input.operation];
|
|
70
|
+
const deadline = timeout === undefined ? signal : AbortSignal.timeout(timeout);
|
|
71
|
+
const response = await new Promise((accept, reject) => {
|
|
72
|
+
// A fresh direct connection keeps local credentials out of HTTP proxy settings.
|
|
73
|
+
const outgoing = httpRequest({
|
|
74
|
+
hostname: '127.0.0.1',
|
|
75
|
+
port: instance.port,
|
|
76
|
+
path: '/v1/player-library',
|
|
77
|
+
method: 'POST',
|
|
78
|
+
agent: false,
|
|
79
|
+
headers: { Authorization: 'Bearer ' + instance.token, 'Content-Type': 'application/json' },
|
|
80
|
+
signal: signal && deadline && deadline !== signal ? AbortSignal.any([signal, deadline]) : deadline,
|
|
81
|
+
}, accept);
|
|
82
|
+
outgoing.once('error', reject);
|
|
83
|
+
outgoing.end(JSON.stringify(input));
|
|
84
|
+
});
|
|
85
|
+
const chunks = [];
|
|
86
|
+
let size = 0;
|
|
87
|
+
for await (const chunk of response) {
|
|
88
|
+
size += chunk.length;
|
|
89
|
+
if (size > 8 * 1024 * 1024)
|
|
90
|
+
throw new Error('The desktop library response exceeds 8 MiB.');
|
|
91
|
+
chunks.push(chunk);
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
status: response.statusCode ?? 500,
|
|
95
|
+
payload: JSON.parse(Buffer.concat(chunks, size).toString('utf8')),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
async function request(instance, input, transport, signal) {
|
|
99
|
+
signal?.throwIfAborted();
|
|
100
|
+
const { status, payload } = await transport(instance, input, signal);
|
|
101
|
+
if (isRecord(payload) && isRecord(payload.error) && typeof payload.error.code === 'string') {
|
|
102
|
+
const message = typeof payload.error.message === 'string' ? ': ' + payload.error.message : '';
|
|
103
|
+
throw Object.assign(new Error(payload.error.code + message), { code: payload.error.code });
|
|
104
|
+
}
|
|
105
|
+
if (status < 200 || status >= 300 || !isRecord(payload) || !isRecord(payload.result))
|
|
106
|
+
throw new Error('The desktop instance returned an invalid response.');
|
|
107
|
+
return payload.result;
|
|
108
|
+
}
|
|
109
|
+
async function liveInstances(requested, { directory = join(homedir(), '.arcadia', 'player-libraries'), transport = postToOwner, signal, }) {
|
|
110
|
+
signal?.throwIfAborted();
|
|
111
|
+
if (requested !== undefined && !instanceId.test(requested))
|
|
112
|
+
throw Object.assign(new Error('Invalid desktop instance id.'), { code: 'DESKTOP_INSTANCE_INVALID' });
|
|
113
|
+
const info = await lstat(directory).catch(error => {
|
|
114
|
+
if (errorCode(error) !== 'ENOENT')
|
|
115
|
+
throw error;
|
|
116
|
+
});
|
|
117
|
+
if (!info)
|
|
118
|
+
return [];
|
|
119
|
+
if (!info.isDirectory() || !privateToUser(info))
|
|
120
|
+
throw new Error('The desktop instance directory must be private to your user.');
|
|
121
|
+
const ids = requested
|
|
122
|
+
? [requested]
|
|
123
|
+
: (await readdir(directory))
|
|
124
|
+
.filter(name => /^[a-f0-9]{32}\.json$/.test(name))
|
|
125
|
+
.map(name => name.slice(0, -5))
|
|
126
|
+
.sort();
|
|
127
|
+
const live = await Promise.all(ids.map(async (id) => {
|
|
128
|
+
const entry = await readInstance(directory, id);
|
|
129
|
+
if (!entry)
|
|
130
|
+
return;
|
|
131
|
+
try {
|
|
132
|
+
const result = await request(entry, { operation: 'describe' }, transport, signal);
|
|
133
|
+
if (result.id === id && result.label === entry.label)
|
|
134
|
+
return entry;
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
// A descriptor can outlive an application that exited unexpectedly.
|
|
138
|
+
}
|
|
139
|
+
}));
|
|
140
|
+
signal?.throwIfAborted();
|
|
141
|
+
return live.filter((instance) => instance !== undefined);
|
|
142
|
+
}
|
|
143
|
+
/** Discover responsive players without exposing their private connection credentials. */
|
|
144
|
+
export async function listDesktopInstances(options = {}) {
|
|
145
|
+
return (await liveInstances(undefined, options)).map(({ id, label }) => ({ id, label }));
|
|
146
|
+
}
|
|
147
|
+
/** Bind each request to one running player. The captured credential never leaves the client. */
|
|
148
|
+
export async function connectDesktopInstance(id, options = {}) {
|
|
149
|
+
const instances = await liveInstances(id, options);
|
|
150
|
+
if (!instances.length)
|
|
151
|
+
throw Object.assign(new Error('No matching running desktop instance. Start the player and list desktop instances.'), { code: 'DESKTOP_INSTANCE_NOT_FOUND' });
|
|
152
|
+
if (instances.length !== 1)
|
|
153
|
+
throw Object.assign(new Error('Multiple desktop instances are running. Choose one with --instance <id>.'), {
|
|
154
|
+
code: 'DESKTOP_INSTANCE_AMBIGUOUS',
|
|
155
|
+
});
|
|
156
|
+
const [instance] = instances;
|
|
157
|
+
return {
|
|
158
|
+
id: instance.id,
|
|
159
|
+
label: instance.label,
|
|
160
|
+
request: (operation, { signal = options.signal } = {}) => request(instance, operation, options.transport ?? postToOwner, signal),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { prepareContentPack } from './testing.js';
|
|
2
|
+
/** Drive both seats at actual host decisions, including roster selection and forced switches. */
|
|
3
|
+
export declare function runEnvironmentDemo(prepared: Awaited<ReturnType<typeof prepareContentPack>>, seed: string): Promise<{
|
|
4
|
+
status: "action-limit" | "completed" | "turn-limit";
|
|
5
|
+
turns: number;
|
|
6
|
+
actions: number;
|
|
7
|
+
winner: string | null;
|
|
8
|
+
}>;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { BattleMessageType } from '@arcadia-eternity/const';
|
|
2
|
+
/** Drive both seats at actual host decisions, including roster selection and forced switches. */
|
|
3
|
+
export async function runEnvironmentDemo(prepared, seed) {
|
|
4
|
+
const system = await prepared.createBattleSession(seed);
|
|
5
|
+
let outcome;
|
|
6
|
+
let failure;
|
|
7
|
+
let actions = 0;
|
|
8
|
+
const unsubscribe = system.BattleEvent(message => {
|
|
9
|
+
if (message.type === BattleMessageType.BattleEnd)
|
|
10
|
+
outcome = message.data;
|
|
11
|
+
if (message.type === BattleMessageType.Error || String(message.type) === BattleMessageType.EffectApplyFail)
|
|
12
|
+
failure = JSON.stringify(message.data);
|
|
13
|
+
});
|
|
14
|
+
try {
|
|
15
|
+
await system.ready();
|
|
16
|
+
const completion = system.waitForCompletion().then(() => null);
|
|
17
|
+
// Worker failures that occur during submission must also be observed.
|
|
18
|
+
void completion.catch(() => { });
|
|
19
|
+
let status = 'completed';
|
|
20
|
+
for (;;) {
|
|
21
|
+
const decision = await Promise.race([system.waitForPendingDecision(), completion]);
|
|
22
|
+
if (!decision || outcome)
|
|
23
|
+
break;
|
|
24
|
+
if (decision.turn >= 300 || actions >= 10000) {
|
|
25
|
+
status = decision.turn >= 300 ? 'turn-limit' : 'action-limit';
|
|
26
|
+
break;
|
|
27
|
+
}
|
|
28
|
+
for (const choices of decision.selections) {
|
|
29
|
+
if (!choices.length)
|
|
30
|
+
continue;
|
|
31
|
+
const action = choices.find(choice => choice.type === 'use-skill') ??
|
|
32
|
+
choices.find(choice => choice.type !== 'surrender') ??
|
|
33
|
+
choices[0];
|
|
34
|
+
await system.submitAction(action);
|
|
35
|
+
actions++;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (failure)
|
|
39
|
+
throw new Error('ENVIRONMENT_DEMO_EFFECT_FAILED: ' + failure);
|
|
40
|
+
const state = await system.getState(undefined, true);
|
|
41
|
+
return {
|
|
42
|
+
status,
|
|
43
|
+
turns: state.currentTurn,
|
|
44
|
+
actions,
|
|
45
|
+
winner: state.players.find(player => player.id === outcome?.winner)?.name ?? null,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
unsubscribe();
|
|
50
|
+
await system.cleanup();
|
|
51
|
+
}
|
|
52
|
+
}
|