@arcadia-eternity/content-sdk 0.0.0-stage → 4.3.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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -2
  3. package/dist/asset-inspect.mjs +67 -0
  4. package/dist/author-api.mjs +112 -0
  5. package/dist/author-reference.mjs +121 -0
  6. package/dist/build-content.mjs +30 -0
  7. package/dist/cli.mjs +74 -0
  8. package/dist/content-query.mjs +283 -0
  9. package/dist/content-workspace.d.mts +161 -0
  10. package/dist/content-workspace.mjs +936 -0
  11. package/dist/debug-environments.mjs +154 -0
  12. package/dist/demo.mjs +22 -0
  13. package/dist/environment-rules.d.mts +5 -0
  14. package/dist/environment-rules.mjs +92 -0
  15. package/dist/environment.mjs +183 -0
  16. package/dist/index.d.mts +1 -0
  17. package/dist/index.mjs +1 -0
  18. package/dist/job-journal.mjs +94 -0
  19. package/dist/jobs.mjs +579 -0
  20. package/dist/lib/content.mjs +95 -0
  21. package/dist/lib/presentation.mjs +240 -0
  22. package/dist/lib/yaml-sharing.mjs +101 -0
  23. package/dist/managed-projects.d.mts +35 -0
  24. package/dist/managed-projects.mjs +303 -0
  25. package/dist/managed-sources.d.mts +19 -0
  26. package/dist/managed-sources.mjs +503 -0
  27. package/dist/mcp-contracts.mjs +153 -0
  28. package/dist/mcp.mjs +369 -0
  29. package/dist/pack-project.mjs +156 -0
  30. package/dist/preview-control.mjs +260 -0
  31. package/dist/preview.mjs +313 -0
  32. package/dist/project-teams.mjs +98 -0
  33. package/dist/project.mjs +140 -0
  34. package/dist/rename.mjs +112 -0
  35. package/dist/setup.mjs +134 -0
  36. package/dist/source-lock.mjs +103 -0
  37. package/dist/template/LICENSE +21 -0
  38. package/dist/template/README.md +17 -0
  39. package/dist/template/arcadia.config.mjs +2 -0
  40. package/dist/template/assets/marks/slow.png +0 -0
  41. package/dist/template/assets/pets/frostling-battle.png +0 -0
  42. package/dist/template/assets/pets/frostling-icon.png +0 -0
  43. package/dist/template/assets/pets/frostling-portrait.png +0 -0
  44. package/dist/template/data/marks/slow.yaml +18 -0
  45. package/dist/template/data/presentations/main.yaml +34 -0
  46. package/dist/template/data/resources/main.yaml +21 -0
  47. package/dist/template/data/skills/rest.yaml +6 -0
  48. package/dist/template/data/skills/strike.yaml +14 -0
  49. package/dist/template/data/species/pet-swf.yaml +36 -0
  50. package/dist/template/data/species/pet.yaml +34 -0
  51. package/dist/template/debug/teams/blue.yaml +25 -0
  52. package/dist/template/debug/teams/orange.yaml +25 -0
  53. package/dist/template/docs/presentation.md +21 -0
  54. package/dist/template/locales/en/mark.yaml +5 -0
  55. package/dist/template/locales/en/skill.yaml +12 -0
  56. package/dist/template/locales/en/species.yaml +6 -0
  57. package/dist/template/locales/zh-CN/mark.yaml +4 -0
  58. package/dist/template/locales/zh-CN/skill.yaml +10 -0
  59. package/dist/template/locales/zh-CN/species.yaml +6 -0
  60. package/dist/template/package.json +44 -0
  61. package/dist/template/skills/arcadia-content-authoring/SKILL.md +23 -0
  62. package/dist/template/skills/arcadia-content-authoring/references/project-sources.md +15 -0
  63. package/dist/template/skills/arcadia-content-authoring/references/tool-workflows.md +37 -0
  64. package/dist/template/skills/seer2-recreate-pet/SKILL.md +82 -0
  65. package/dist/template/skills/seer2-recreate-pet/references/mechanics-and-validation.md +47 -0
  66. package/dist/template/skills/seer2-recreate-pet/references/project-conventions.md +32 -0
  67. package/dist/template/skills/seer2-recreate-pet/references/testing.md +50 -0
  68. package/dist/template/src/effects.ts +44 -0
  69. package/dist/template/test/pack.test.mjs +178 -0
  70. package/dist/template/tsconfig.json +15 -0
  71. package/dist/testing.mjs +204 -0
  72. package/dist/workbench-context.mjs +18 -0
  73. package/dist/workspace-cli.mjs +60 -0
  74. package/dist/workspace-materials.mjs +153 -0
  75. package/dist/workspace.mjs +684 -0
  76. package/package.json +68 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Arcadia Eternity contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,99 @@
1
- # Temporary Holding Version
1
+ # Arcadia Content SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@arcadia-eternity/content-sdk` is the development dependency for a content pack. It provides TypeScript effect types, testing helpers, and the `arcadia-content` and `arcadia-content-mcp` executables. The bundled template includes data, effects, scenario configuration and behavior tests.
4
+
5
+ ```json
6
+ {
7
+ "scripts": {
8
+ "check": "arcadia-content check",
9
+ "build": "arcadia-content build",
10
+ "rename": "arcadia-content rename",
11
+ "demo": "npm run build && arcadia-content demo",
12
+ "preview": "npm run build && arcadia-content preview",
13
+ "pack": "arcadia-content pack"
14
+ }
15
+ }
16
+ ```
17
+
18
+ Commands use the caller's working directory. `check` checks `tsconfig.json` and recursive JSON/YAML sources in `data/{species,skills,marks,behaviors}`. `build` compiles TypeScript and generates `dist/content.json`. `rename --name ... --project-id ... --namespace ...` changes local structured references while preserving foreign references, content IDs and YAML comments. `pack` checks, builds and stages a publishable package before running `npm pack --ignore-scripts`.
19
+
20
+ For code packages, `pack` bundles the effect dependency graph into `dist/arcadia-effects.json` and adds `arcadia.effectArtifact` to the staged manifest. Source `package.json` stays unchanged. This author-side compilation parses and bundles code without evaluating module initialization or effect factories. Consumers can prepare the resulting package with `effectPreparation: 'prebuilt-only'`; they do not need to compile author source or install its development dependencies. Plain `npm pack` does not generate this artifact, so use `npm run pack` or `arcadia-content pack` for distribution. Publication of a prebuilt artifact does not grant authority to execute its code.
21
+
22
+ `demo` loads `arcadia.config.mjs`, whose default export selects two project teams with `teams: ['blue', 'orange']`. The template stores their portable configurations in `debug/teams/*.yaml`. It packs the project, installs the artifact in a temporary npm project and runs a deterministic local battle using each player's first skill. It fails on effect errors or if the battle exceeds 40 turns. The configuration and behavioral assertions belong to the content pack.
23
+
24
+ `workspace <directory> preview --execute` and MCP `preview_start` capture saved sources, build and install the candidate, and keep a loopback Node host running for the existing full battle client. The first configured player is interactive and the second is AI. The result supplies `preview.endpoint`, `preview.clientPath` and, when `ARCADIA_PREVIEW_CLIENT_URL` is set, `preview.url`. The desktop opens the same candidate in an isolated window. `arcadia-content preview` serves an already built project; stop it with Ctrl+C.
25
+
26
+ Task receipts live in `.arcadia/author-jobs`, outside exports and source revisions. `workspace <directory> job --execute` and `cancel --execute` accept `{ "jobId": "..." }` on stdin; MCP uses `job_get` and `job_cancel`. These operations work across author sessions. A stopped owner becomes `interrupted` on the next query. New candidates never replace older preview processes, failed preparations keep existing previews, and changed source marks old receipts stale. At most four preview processes are retained per session. Leaving the desktop editor clears its context and draft markers while active previews keep their owner alive. Explicit cancellation, forgetting the project, closing a CLI/MCP owner, or quitting the application terminates the corresponding previews and releases temporary files. This journal restores task status, not live processes or battle saves after a host restart.
27
+
28
+ Tests can import `prepareBattleEnvironment`, `prepareContentPack`, `attack`, `nextTurn`, `cancelled` and `runBattle` from `@arcadia-eternity/content-sdk/testing`. `prepareContentPack(root = process.cwd(), { offline = true, cache })` loads that config and returns the installed `environment`, `manifest`, packed `files`, `await createBattle(seed)`, `contentFor(battle)`, `await restoreBattle(snapshot)`, `track(battle)` and async `dispose()`. Environment preparation reads and compiles data without evaluating effect code. Each explicit reference battle owns fresh VMs, released by its cleanup. The harness admits code only in the temporary local-development project. It uses the normal npm cache by default; `cache` selects an explicit cache directory. It defaults to offline artifact installation; packs with runtime dependencies need a populated cache or an explicit `{ offline: false }`.
29
+
30
+ ## YAML sharing in author workspaces
31
+
32
+ Source workspaces and content/locale builds resolve anchors, aliases and `<<` merges with the existing `yaml` library. Snapshot records include `sharedFields`: record-relative paths, the sharing reason (`anchor`, `alias`, or `merge`), anchor name, document-relative definition path and one-based source line/column.
33
+
34
+ Forms display shared values read-only and can open their definition in an external editor. This includes referenced anchor definitions themselves. Explicit local overrides of merged fields remain editable. Collection controls that would replace a subtree containing shared nodes are disabled. `saveRecord` independently checks the current document's sharing metadata, rejects shared changes with `SHARED_FIELD_READ_ONLY`, edits independent YAML nodes, and verifies both resulting values and anchor/alias structure before writing. No-op saves preserve the original text; other saves may normalize formatting and do not promise byte-for-byte preservation.
35
+
36
+ Source-text editing (external editors and version-checked CLI/MCP writes) remains available for intentionally changing sharing. External changes invalidate stale form saves. Unresolved aliases, cycles and excessive alias expansion produce diagnostics without rewriting the source. This does not add cross-file YAML anchors, automatic shared edits, or detach/override actions to forms. Localized names/descriptions resolve sharing when read, edited and built; shared text fields remain read-only in forms.
37
+
38
+ ## npm installation
39
+
40
+ After the npm release, install `@arcadia-eternity/content-sdk` as a dev dependency. Import effect types from the package root and scenario helpers from `@arcadia-eternity/content-sdk/testing`. Both author commands are included. See [installation instructions](../../docs/guides/ugc-npm-release.md).
41
+
42
+ ## Local development SDK
43
+
44
+ For an unpublished host build, build and stage packages from a trusted checkout:
45
+
46
+ ```sh
47
+ pnpm --filter @arcadia-eternity/content-sdk... --filter @arcadia-eternity/protocol... run build
48
+ node scripts/stage-author-sdk.mjs /new/author-sdk
49
+ cd /path/to/content-pack
50
+ node /path/to/main-repo/packages/content-dev/src/setup.mjs --sdk-dir /new/author-sdk
51
+ ```
52
+
53
+ The installer checks the seven required archives and SDK API version, installs the tool and SDK together without changing the pack's package metadata or creating a lockfile, and records the installation under `.arcadia/`.
54
+
55
+ The optional source-bootstrap `setup:source` entry in the independent template fetches this repository's `src/setup.mjs` from the exact revision in `arcadia-sdk.json`. This standalone installer uses only Node built-ins. It builds the pinned source with its lockfile, stages the development tool and SDK, and installs them. There is no copied installer in the template. After installation, `npm exec --offline -- arcadia-content setup --sdk-dir ... --offline` supports cached/offline updates. Normal template installation uses the registry release and a standard npm lockfile; the source bootstrap remains available for local SDK development.
56
+
57
+ ## Object drafts and reviewed saves
58
+
59
+ The desktop workbench keeps definition and localized name/description drafts while navigating between species, skills, marks and resource usages. References are selected from existing project content. Source paths live in expandable details; code and file organization remain external workflows. The workbench can create records and relationships as drafts, import media files, and edit separate resource definitions and presentation bindings. Imports copy files immediately; structured changes are reviewed before saving. Descriptions use the existing FormatJS renderer with current draft values and mark links. Missing or ambiguous language files must be resolved externally; the form can add a name/description entry for an existing object to an existing language file.
60
+
61
+ `snapshot.localeSources` exposes language, namespace, file revision, text entries and shared-field provenance. `workspace.saveChanges({ changes })`, session operation `save`, CLI `workspace <directory> save` and MCP `content_apply` share the same structured save path. Each change supplies `kind: record | locale`, `file`, `expectedVersion`, and the complete `record`; definition changes also supply the original `index` (or null), and locale changes supply `id`. The service prepares all changes before writing, combines edits to the same file, and reports `{ complete, results }` with individual saved file revisions. Files commit separately: on failure, already-saved files remain saved and remaining drafts must be retained. This is not a cross-file transaction.
62
+
63
+ External changes refresh clean views. Dirty sources pause saving and show original/draft/latest values. Every locally changed field requires an explicit choice; untouched fields take the latest source value. Reconciliation updates the draft and its base revision only, and requires a separate save review. Missing, invalid or ambiguous sources keep the draft blocked. A uniquely identified object moved to another source can adopt that location after explicit reconciliation; the old file is never recreated by a form save.
64
+
65
+ ## Live workbench context
66
+
67
+ The desktop MCP configuration includes an optional `--context-file` path under Electron userData, outside package sources. `workspace_context` returns current view/focus, locale, draft values and conflicts without requiring an object selection. Focus is not an authorization scope. Disk queries and version-checked writes remain unchanged; unsaved values must not be treated as disk state. Context is cleared on workspace close and expires after 90 seconds without a heartbeat. Standalone connections without the option report `not-configured`.
68
+
69
+ ## MCP discovery and page collaboration
70
+
71
+ `content_query` accepts exact `id`, `contentKind`, `locale`, `namespace`, `packageName` and `scope: project | dependencies | all`. Search includes localized names. The default `detail: summary` returns identity, source and display fields; request `detail: full` before editing to obtain complete records and YAML sharing information. Locale results paginate individual object entries. Results include `nextOffset` and diagnostics. Dependency discovery reads declared installed runtime dependencies without importing effects; dependency rows are read-only, and their package-relative paths are not bound-project source paths.
72
+
73
+ `job_list` discovers retained tasks across sessions. `job_get` returns status, phase, bounded diagnostics and candidate metadata without logs by default; `waitMs` (at most 10000) waits briefly for changes. `job_output` reads bounded incremental logs using UTF-16 code-unit cursors: reuse `nextCursor`, inspect `hasMore`, and treat `truncated` as a missing prefix. `job_get` can also include one chunk with `includeOutput: true` and `afterCursor`. Existing direct job and CLI operations retain their original full result shapes.
74
+
75
+ `team_list`, `team_save`, `team_remove`, `environment_list` and `environment_save` use the same project services as the desktop. Writes require an expected file version; null means create. They do not select teams/environments, replace local drafts, install dependencies or change an active battle. The desktop relays project file changes to the matching workbench/preview window: clean values refresh, while dirty drafts are retained and external changes are surfaced for explicit resolution. Focus refresh and pre-launch checks remain fallbacks. Current battles retain their launch snapshot.
76
+
77
+ Cooperating author processes serialize version checks and writes within each project under `.arcadia/author-locks`, outside source revisions. Busy writes fail after bounded waiting; a live writer is never displaced. This coordinates the desktop, CLI and MCP, not arbitrary external editors, and does not make multi-file saves transactional. Context describes unsaved content but does not lock a project: MCP writes update disk, while the desktop retains dirty drafts and their base versions for explicit reconciliation. File-version conflicts remain authoritative even if context has expired. Partial `content_apply` results set `isError` and retain per-file receipts.
78
+
79
+ `author_reference` and `arcadia://authoring/<topic>` provide installed SDK schemas/examples for species, skills, marks, teams, environments, descriptions and effects. Parser schema notes distinguish linked runtime data from source references. `asset_inspect` returns metadata for a declared resource ID; `includeImage` returns local image bytes up to 2 MiB as standard MCP image content. MIME types follow source filenames via `mime-types`; unknown extensions remain metadata-only. Decoding and display belong to the MCP client: no image dimension parsing, container validation or transcoding is performed, and `imageAvailable` indicates transport eligibility rather than decodability. Remote URLs are metadata only, with no fetching or caching; audio and SWF are not executed.
80
+
81
+ Execution-enabled sessions expose `battle_create`, `battle_read`, `battle_events`, `battle_action`, `battle_reset` and `battle_close`. Supply a running preview `jobId`; creation requires two saved team IDs and a fixed seed. Creation and reset read the latest saved team files and retain their versions in that automation battle. They use the captured candidate rules without rebuilding for team-only changes. These tools never operate on the human preview battle or local team drafts. Mutations require `sessionId` and `expectedRevision`; submit a selection returned by `battle_read`. Events use bounded cursor pagination. A failed engine step returns its revision and diagnosis with `stateCurrent: false`, allowing reset/close while preserving the last valid state. At most four automation battles exist per preview; stopping the preview releases all of them. A stale candidate remains an old-source result.
82
+
83
+ ## Project teams and named environments
84
+
85
+ See [the workflow contract](../../docs/guides/project-battle-workflow.md). `prepareContentPack(root, { environmentId, sources, lockRoot, offline, cache })` selects a named environment; omit `environmentId` for the declared-dependencies-only package test. `sources` maps npm names to local source directories. `lockRoot` opts into version-checked npm lock writes to the original project; without it preparation does not mutate project files. The returned harness exposes `loadTeams([firstId, secondId])` and `teamVersions` so automatic cases explicitly select their inputs. Manual drafts and last-selected teams never enter automatic tests. Only `config.teams` defines the default team selection.
86
+
87
+ Environment schema v2 adds versioned rule data and runtime requirements. Existing v1 files remain readable and are upgraded only on an explicit save. Reference battles and Worker battles apply the same team-size, species uniqueness and content allow/deny rules. Unsupported tiers or capability requirements fail explicitly. Editing returned environment metadata does not change an already prepared candidate's admission policy.
88
+
89
+ ## Shared management workspace
90
+
91
+ `@arcadia-eternity/content-sdk/management-workspace` exports the typed `ContentWorkspace` API used by desktop owners and servers. One process owns each workspace; another live writer is rejected, while a confirmed dead process owner can be recovered. `saveDraft` requires the current revision. `prepareVersion` captures and statically validates a fixed npm installation, while `adoptVersion` borrows existing client materials through a material-owner lease without another installation. Long preparation accepts an abort signal and a trusted `beforeCommit` authorization check.
92
+
93
+ Workspace files own environment definitions and immutable versions. Database adapters supply durable retention roots; runtime leases belong to the current owner. Deletion fails closed when retention information is unavailable, and owner shutdown refuses outstanding runtime leases. Server bindings, accounts, grants and running rooms remain separate from these files.
94
+
95
+ `exportVersion` creates a portable environment archive with standard npm locks and material bytes, excluding server and workspace identities. `exportSnapshot` captures workspace identity, drafts and fixed versions for a server backup. `restoreSnapshot` requires an empty, inactive staging workspace: restore preserves identities, clone remaps them. The server backup coordinator validates the corresponding database snapshot before switching the full server directory. These file APIs do not provide a transaction spanning the database and filesystem.
96
+
97
+ ## Repository development
98
+
99
+ `pnpm --filter @arcadia-eternity/content-sdk watch` builds once, then rebuilds when `src`, `template`, or either bundled skill directory under `docs/guides` changes. Rebuilds are serialized, include deletions, and recover after a failed build. The root `pnpm watch` includes this watcher. `pnpm --filter @arcadia-eternity/content-sdk clear` removes `dist`; root `pnpm clear` includes it as well. The package `typecheck` validates public `.d.mts` declarations; Node tests validate the JavaScript implementation.
@@ -0,0 +1,67 @@
1
+ import { stat } from 'node:fs/promises'
2
+ import { lookup } from 'mime-types'
3
+ import { validResourceId } from './lib/presentation.mjs'
4
+ import { WorkspaceError } from './workspace.mjs'
5
+
6
+ export const imageByteLimit = 2 * 1024 * 1024
7
+ const fail = (code, message) => {
8
+ throw new WorkspaceError(code, message)
9
+ }
10
+
11
+ /** Read declared local resources only; remote URLs remain metadata and are never fetched. */
12
+ export async function inspectAsset(workspace, { id, includeImage = false } = {}) {
13
+ if (!validResourceId(id)) fail('RESOURCE_INVALID', '需要已声明资源的稳定 ID')
14
+ if (typeof includeImage !== 'boolean') fail('RESOURCE_INVALID', 'includeImage 必须是布尔值')
15
+ const snapshot = await workspace.snapshot()
16
+ const resources = snapshot.records.filter(row => row.kind === 'resources' && row.record.id === id)
17
+ if (!resources.length) fail('RESOURCE_UNKNOWN', '此项目没有声明该资源')
18
+ if (resources.length !== 1) fail('RESOURCE_AMBIGUOUS', '资源 ID 不唯一,请先修复重复声明')
19
+ const definition = resources[0]
20
+ const { kind, source } = definition.record
21
+ if (typeof source !== 'string') fail('RESOURCE_INVALID', '资源缺少有效位置')
22
+ const metadata = { id, kind, source, definition: definition.file, definitionVersion: definition.version }
23
+ if (/^https?:\/\//.test(source)) {
24
+ let url
25
+ try {
26
+ url = new URL(source)
27
+ } catch {
28
+ fail('RESOURCE_INVALID', '资源 URL 无效')
29
+ }
30
+ if (url.username || url.password) fail('RESOURCE_INVALID', '资源 URL 不能含有凭据')
31
+ return { metadata: { ...metadata, remote: true, imageAvailable: false, reason: 'REMOTE_NOT_FETCHED' } }
32
+ }
33
+ const path = await workspace.path(source)
34
+ const info = await stat(path)
35
+ if (!info.isFile()) fail('RESOURCE_INVALID', '资源必须是普通文件')
36
+ // Follow the source filename, as the authoring resource pipeline does. Decoding belongs to the client.
37
+ const mimeType = lookup(source) || 'application/octet-stream'
38
+ if (kind !== 'image' && mimeType.startsWith('image/'))
39
+ fail('RESOURCE_KIND_MISMATCH', '声明的资源类型与图片文件名不同')
40
+ const reason =
41
+ kind !== 'image'
42
+ ? 'NOT_IMAGE'
43
+ : !mimeType.startsWith('image/')
44
+ ? 'IMAGE_FORMAT_UNKNOWN'
45
+ : info.size > imageByteLimit
46
+ ? 'IMAGE_TOO_LARGE'
47
+ : undefined
48
+ const result = {
49
+ metadata: {
50
+ ...metadata,
51
+ remote: false,
52
+ bytes: info.size,
53
+ mimeType,
54
+ imageAvailable: !reason,
55
+ ...(reason ? { reason } : {}),
56
+ imageByteLimit,
57
+ },
58
+ }
59
+ if (!includeImage) return result
60
+ if (reason) fail(reason, '此资源不能直接返回图片;请读取元数据或在页面查看')
61
+ const asset = await workspace.asset(source)
62
+ if (asset.bytes.length > imageByteLimit) fail('IMAGE_TOO_LARGE', '图片超过 2 MiB')
63
+ result.metadata.bytes = asset.bytes.length
64
+ result.metadata.version = asset.version
65
+ result.image = { type: 'image', mimeType, data: asset.bytes.toString('base64') }
66
+ return result
67
+ }
@@ -0,0 +1,112 @@
1
+ import { DebugEnvironments } from './debug-environments.mjs'
2
+ import { ProjectTeams } from './project-teams.mjs'
3
+ import { AuthorWorkspace, WorkspaceError } from './workspace.mjs'
4
+ import { readWorkbenchContext } from './workbench-context.mjs'
5
+ import { AuthorJobs } from './jobs.mjs'
6
+ import { queryContent } from './content-query.mjs'
7
+ import { authorReference } from './author-reference.mjs'
8
+ import { inspectAsset } from './asset-inspect.mjs'
9
+ import { callPreviewControl } from './preview-control.mjs'
10
+ export { createSourceProject, connectDevelopmentSdk, authorConnection } from './project.mjs'
11
+ export { ContentWorkspace } from './content-workspace.mjs'
12
+ export { normalizeEnvironmentDocument } from './debug-environments.mjs'
13
+
14
+ /** Shared operations for the desktop, CLI and MCP adapters. */
15
+ export async function openAuthorSession(directory, options = {}) {
16
+ const workspace = await AuthorWorkspace.open(directory, options)
17
+ const jobs = new AuthorJobs(workspace, options)
18
+ await jobs.initialize()
19
+ return {
20
+ workspace,
21
+ jobs,
22
+ teams: new ProjectTeams(workspace),
23
+ environments: new DebugEnvironments(workspace),
24
+ async describe() {
25
+ const snapshot = await workspace.snapshot()
26
+ return {
27
+ protocolVersion: 1,
28
+ root: snapshot.root,
29
+ name: snapshot.name,
30
+ project: snapshot.project,
31
+ sourceRevision: await workspace.revision(),
32
+ capabilities: { ...snapshot.capabilities, codeExecution: !workspace.readOnly && jobs.execute },
33
+ diagnostics: snapshot.diagnostics,
34
+ }
35
+ },
36
+ async query(input = {}) {
37
+ return queryContent(workspace, input)
38
+ },
39
+ async call(operation, input = {}) {
40
+ switch (operation) {
41
+ case 'context':
42
+ return readWorkbenchContext(options.contextFile, workspace.root)
43
+ case 'describe':
44
+ return this.describe()
45
+ case 'query':
46
+ return this.query(input)
47
+ case 'reference':
48
+ return authorReference(input)
49
+ case 'asset-inspect':
50
+ return inspectAsset(workspace, input)
51
+ case 'snapshot':
52
+ return workspace.snapshot()
53
+ case 'read':
54
+ return workspace.read(input.file)
55
+ case 'write':
56
+ if (options.readOnly) throw new WorkspaceError('WRITE_DISABLED', '此会话为只读')
57
+ return workspace.write(input)
58
+ case 'save':
59
+ if (options.readOnly) throw new WorkspaceError('WRITE_DISABLED', '此会话为只读')
60
+ return workspace.saveChanges(input)
61
+ case 'start':
62
+ return jobs.start(input)
63
+ case 'job':
64
+ await jobs.refresh()
65
+ return jobs.get(input.jobId)
66
+ case 'jobs':
67
+ await jobs.refresh()
68
+ return jobs.list()
69
+ case 'job-query':
70
+ return jobs.queryJob(input)
71
+ case 'jobs-query':
72
+ return jobs.queryJobs(input)
73
+ case 'job-output':
74
+ return jobs.readJobOutput(input)
75
+ case 'cancel-query':
76
+ await jobs.refresh()
77
+ await jobs.cancel(input.jobId)
78
+ return jobs.queryJob({ jobId: input.jobId })
79
+ case 'team-list':
80
+ return { items: await this.teams.list() }
81
+ case 'team-save':
82
+ return this.teams.save(input)
83
+ case 'team-remove':
84
+ await this.teams.remove(input)
85
+ return { id: input.id, removed: true }
86
+ case 'environment-list':
87
+ return { items: await this.environments.list() }
88
+ case 'environment-save':
89
+ return this.environments.save(input)
90
+ case 'battle': {
91
+ if (workspace.readOnly || !jobs.execute)
92
+ throw new WorkspaceError('EXECUTION_DISABLED', '自动化对局需要可执行的作者会话。')
93
+ await jobs.refresh()
94
+ const job = jobs.get(input.jobId)
95
+ if (job.kind !== 'preview' || job.state !== 'succeeded' || !job.result?.preview?.endpoint)
96
+ throw new WorkspaceError('PREVIEW_NOT_ACTIVE', '此任务没有运行中的试玩候选。')
97
+ const { jobId: _jobId, operation: action, ...args } = input
98
+ return callPreviewControl(job.result.preview.endpoint, action, args)
99
+ }
100
+ case 'cancel':
101
+ await jobs.refresh()
102
+ return jobs.cancel(input.jobId)
103
+ default:
104
+ throw new WorkspaceError('OPERATION_INVALID', '不支持的作者操作')
105
+ }
106
+ },
107
+ async close() {
108
+ await jobs.close()
109
+ await workspace.close()
110
+ },
111
+ }
112
+ }
@@ -0,0 +1,121 @@
1
+ import { readFile } from 'node:fs/promises'
2
+ import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js'
3
+ import { NativeSpeciesSchema, NativeSkillSchema, NativeMarkSchema } from '@arcadia-eternity/battle/engine'
4
+ import { teamEnvelopeSchema, portablePetSchema } from './project-teams.mjs'
5
+ import { EnvironmentDocumentSchema } from './debug-environments.mjs'
6
+ import { WorkspaceError } from './workspace.mjs'
7
+
8
+ export const referenceTopics = ['species', 'skills', 'marks', 'team', 'environment', 'descriptions', 'effects']
9
+ const parserSchemas = { species: NativeSpeciesSchema, skills: NativeSkillSchema, marks: NativeMarkSchema }
10
+ const examples = { species: 'data/species/pet.yaml', skills: 'data/skills/strike.yaml', marks: 'data/marks/slow.yaml' }
11
+
12
+ async function template(file) {
13
+ try {
14
+ return await readFile(new URL(`./template/${file}`, import.meta.url), 'utf8')
15
+ } catch (error) {
16
+ if (error.code !== 'ENOENT') throw error
17
+ return readFile(new URL(`../template/${file}`, import.meta.url), 'utf8')
18
+ }
19
+ }
20
+
21
+ /** Discover installed SDK contracts, without importing a content project's executable effects. */
22
+ export async function authorReference({ topic } = {}) {
23
+ if (!referenceTopics.includes(topic)) throw new WorkspaceError('REFERENCE_UNKNOWN', '请选择有效的作者参考主题')
24
+ if (parserSchemas[topic]) {
25
+ return {
26
+ topic,
27
+ title: `${topic}: parser fields and source example`,
28
+ source: '@arcadia-eternity/battle/engine',
29
+ stage: 'linked-runtime',
30
+ schema: toJsonSchemaCompat(parserSchemas[topic]),
31
+ examples: [{ language: 'yaml', text: await template(examples[topic]) }],
32
+ notes: [
33
+ 'This is the actual parser schema AFTER package linking, not a validator for unlinked source documents. JSON Schema cannot express every Zod refinement; run check and tests.',
34
+ 'Source IDs are local stable IDs. Package linking produces namespace:id runtime IDs. Official base references retain their existing IDs.',
35
+ 'Source relationship slots use {$ref:{projectId,kind,id}} for package content: species learnable_skills[].skill_id uses kind skill; ability/emblem use mark; skills/marks behaviors[].definitionId uses behavior. Declare dependencies and resolve actual IDs before writing.',
36
+ 'Keep rules, data/presentations, data/resources and localized names/descriptions separate. Do not infer behavior from description text.',
37
+ ],
38
+ }
39
+ }
40
+ if (topic === 'team') {
41
+ const schema = toJsonSchemaCompat(teamEnvelopeSchema)
42
+ schema.properties.team.items = JSON.parse(JSON.stringify(portablePetSchema))
43
+ return {
44
+ topic,
45
+ title: 'Portable project team',
46
+ source: '@arcadia-eternity/content-sdk/project-teams',
47
+ stage: 'source',
48
+ schema,
49
+ examples: [{ language: 'yaml', text: 'schemaVersion: 1\nid: blue\nname: 蓝队\nteam: []\n' }],
50
+ notes: [
51
+ 'Save debug/teams/<id>.yaml with expectedVersion. Pets have no runtime id. Order determines the lead pet; an empty team is editable but cannot start a battle.',
52
+ 'Saving project teams does not change local page drafts, selected teams or an already running battle. Re-read before retrying a conflict.',
53
+ ],
54
+ }
55
+ }
56
+ if (topic === 'environment') {
57
+ return {
58
+ topic,
59
+ title: 'Named project environment',
60
+ source: '@arcadia-eternity/content-sdk/debug-environments',
61
+ stage: 'source',
62
+ schema: toJsonSchemaCompat(EnvironmentDocumentSchema),
63
+ examples: [
64
+ {
65
+ language: 'json',
66
+ text: JSON.stringify({ schemaVersion: 1, id: 'interaction', name: '双包交互', packages: {}, sources: [] }),
67
+ },
68
+ ],
69
+ notes: [
70
+ 'default is built in and cannot be saved as a named environment. Names must be nonblank; source package names must be unique.',
71
+ 'packages accepts registry version constraints, never file:/link:/workspace: or filesystem paths. sources lists package names already mapped locally; it does not contain paths.',
72
+ 'Save with expectedVersion. Updating a named environment neither selects it in the page nor changes a running candidate; prepare a new preview explicitly.',
73
+ ],
74
+ }
75
+ }
76
+ if (topic === 'effects') {
77
+ return {
78
+ topic,
79
+ title: 'Native TypeScript effects',
80
+ source: '@arcadia-eternity/content-sdk/dist/template/src/effects.ts',
81
+ examples: [{ language: 'typescript', text: await template('src/effects.ts') }],
82
+ notes: [
83
+ 'Import EffectModuleContext from @arcadia-eternity/content-sdk and use the host-supplied SDK. Importing an effect module must not register global state.',
84
+ 'defineCodeEffect uses triggers/apply. ctx.trigger identifies the trigger; ctx.parent is the typed parent context. Use stable namespaced IDs and actual behavior definitions.',
85
+ 'This installed template is the executable example. Query content, read source versions, check, and run behavior tests after edits. No Rule Graph/DSL conversion is needed.',
86
+ ],
87
+ }
88
+ }
89
+ return {
90
+ topic,
91
+ title: 'ICU descriptions and semantic tags',
92
+ source: 'docs/guides/content-presentation.md; packages/web-ui/src/i18n/richDescription.ts',
93
+ tags: [
94
+ 'markName',
95
+ 'status',
96
+ 'guaranteedHit',
97
+ 'damage',
98
+ 'heal',
99
+ 'shield',
100
+ 'buff',
101
+ 'debuff',
102
+ 'rage',
103
+ 'strong',
104
+ 'emphasis',
105
+ 'mark',
106
+ ],
107
+ examples: [
108
+ {
109
+ language: 'text',
110
+ text: '造成 <damage>{power}</damage> 点伤害,并附加 <mark>example-content-pack:slow</mark>。',
111
+ },
112
+ ],
113
+ notes: [
114
+ 'Names are plain text. Descriptions use ICU flat variables such as {power}, plural/select, and the listed semantic tags; no Markdown, HTML attributes, dotted expressions, or legacy color codes.',
115
+ 'Only scalar public values from the actual rendering context are available. Definition previews have no live stack and preserve {stack}; battle descriptions use the real instance stack.',
116
+ 'markName highlights ordinary marks in cyan. status highlights the adverse/exceptional display subclass in orange. guaranteedHit describes the skill property in lime. Do not modify gameplay tags merely for color.',
117
+ '<mark>namespace:id</mark> is the current mark reference. Plain highlighted names are not identities. Resolve real dependency-visible targets; never guess a matching object by name.',
118
+ 'A general cross-kind reference protocol, exhaustive variable contract and shared reference-integrity validator are not implemented. Formatting checks do not prove all references are valid.',
119
+ ],
120
+ }
121
+ }
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ import { mkdir, rename, rm, writeFile } from 'node:fs/promises'
3
+ import { join, resolve } from 'node:path'
4
+ import { readContentSources, assembleContent } from './lib/content.mjs'
5
+ import { buildPresentation } from './lib/presentation.mjs'
6
+
7
+ const args = process.argv.slice(2)
8
+ if (args.length && (args.length !== 1 || args[0] !== '--check')) throw new Error('Usage: build-content.mjs [--check]')
9
+ const root = resolve('.')
10
+ const sources = await readContentSources(root)
11
+ const content = assembleContent(sources)
12
+ const presentation = await buildPresentation(root, sources)
13
+ if (!args.includes('--check')) {
14
+ const directory = join(root, 'dist')
15
+ await mkdir(directory, { recursive: true })
16
+ const temporary = join(directory, `content.${process.pid}.tmp`)
17
+ try {
18
+ await writeFile(temporary, JSON.stringify(content, null, 2) + '\n', { flag: 'wx' })
19
+ await writeFile(join(directory, 'presentation.json.tmp'), JSON.stringify(presentation, null, 2) + '\n')
20
+ await rename(join(directory, 'presentation.json.tmp'), join(directory, 'presentation.json'))
21
+ await rename(temporary, join(directory, 'content.json'))
22
+ } finally {
23
+ await rm(temporary, { force: true })
24
+ }
25
+ }
26
+ console.log(
27
+ `${args.includes('--check') ? 'Checked' : 'Built'} ${sources.length} data files: ${Object.entries(content.data)
28
+ .map(([kind, records]) => `${kind}=${records.length}`)
29
+ .join(', ')}`,
30
+ )
package/dist/cli.mjs ADDED
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process'
3
+ import { createRequire } from 'node:module'
4
+ import { fileURLToPath } from 'node:url'
5
+ const require = createRequire(import.meta.url)
6
+ const [command, ...args] = process.argv.slice(2)
7
+ const help = `arcadia-content <command>
8
+ check Check TypeScript and JSON/YAML content
9
+ build Compile TypeScript and assemble content/media/locales metadata
10
+ rename Change package/project/namespace identities and local references
11
+ demo Run the battle configured in arcadia.config.mjs
12
+ preview Prepare a local candidate for the full battle client; stop with Ctrl+C
13
+ pack Check, build and create an npm content package
14
+ setup Install the pinned development SDK and tool
15
+ workspace <directory> <operation> [--execute] Structured author operations
16
+ `
17
+ function run(file, arguments_) {
18
+ return new Promise((resolve, reject) => {
19
+ const child = spawn(file, arguments_, { stdio: 'inherit', cwd: process.cwd() })
20
+ child.on('error', reject)
21
+ child.on('exit', (code, signal) =>
22
+ code === 0 ? resolve() : reject(new Error(`${file} failed (${signal ?? code})`)),
23
+ )
24
+ })
25
+ }
26
+ const modulePath = name => fileURLToPath(new URL(name, import.meta.url))
27
+ async function data(check = false) {
28
+ await run(process.execPath, [modulePath('./build-content.mjs'), ...(check ? ['--check'] : [])])
29
+ }
30
+ async function types(check = false) {
31
+ await run(process.execPath, [
32
+ require.resolve('typescript/bin/tsc'),
33
+ '-p',
34
+ 'tsconfig.json',
35
+ ...(check ? ['--noEmit'] : []),
36
+ ])
37
+ }
38
+ async function build() {
39
+ await data(true)
40
+ await types()
41
+ await data()
42
+ }
43
+ try {
44
+ if (!command || command === '--help' || command === '-h') console.log(help)
45
+ else if (command === 'workspace') {
46
+ const { workspaceCli } = await import('./workspace-cli.mjs')
47
+ await workspaceCli(args)
48
+ } else if (command === 'setup') {
49
+ const { setup } = await import('./setup.mjs')
50
+ await setup(args)
51
+ } else if (command === 'rename') await run(process.execPath, [modulePath('./rename.mjs'), ...args])
52
+ else {
53
+ if (!['check', 'build', 'demo', 'preview', 'pack'].includes(command) || args.length)
54
+ throw new Error(`Unknown command or option.\n${help}`)
55
+ if (command === 'check') {
56
+ await data(true)
57
+ await types(true)
58
+ } else if (command === 'build') await build()
59
+ else if (command === 'demo') await import('./demo.mjs')
60
+ else if (command === 'preview') await (await import('./preview.mjs')).previewCommand()
61
+ else {
62
+ await build()
63
+ const { packBuiltProject } = await import('./pack-project.mjs')
64
+ const packed = await packBuiltProject()
65
+ console.log(`Packed ${packed.filename}`)
66
+ console.log(
67
+ `ARCADIA_RESULT=${JSON.stringify({ filename: packed.filename, integrity: packed.integrity, shasum: packed.shasum, files: packed.files.map(file => file.path) })}`,
68
+ )
69
+ }
70
+ }
71
+ } catch (error) {
72
+ console.error(error.message)
73
+ process.exitCode = 1
74
+ }