@craft_eco/craft-mcp 0.1.14 → 0.1.18

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 (27) hide show
  1. package/README.md +1 -1
  2. package/dist-server/game-workflow/draft-archive.mjs +53 -91
  3. package/dist-server/game-workflow/draft-uploads.mjs +207 -207
  4. package/dist-server/game-workflow/publications.mjs +4 -2
  5. package/dist-server/mcp/control-panel.mjs +59 -40
  6. package/dist-server/mcp/publication-page.html +86 -0
  7. package/dist-server/mcp/publication-page.mjs +347 -0
  8. package/dist-server/mcp/publication-preview.mjs +49 -0
  9. package/dist-server/mcp/publication-tools.mjs +4 -1
  10. package/dist-server/mcp/publish-panel.mjs +191 -0
  11. package/dist-server/mcp/server.mjs +312 -297
  12. package/dist-server/upstream/craft-aigc.mjs +169 -197
  13. package/dist-server/upstream/publication-transport.mjs +2 -1
  14. package/package.json +1 -1
  15. package/resources/craft-game-maker/SKILL.md +69 -67
  16. package/vendor/agent-cli/dist/src/artifacts/external-game-archive.d.ts +19 -0
  17. package/vendor/agent-cli/dist/src/artifacts/external-game-archive.d.ts.map +1 -0
  18. package/vendor/agent-cli/dist/src/artifacts/external-game-archive.js +107 -0
  19. package/vendor/agent-cli/dist/src/artifacts/external-game-archive.js.map +1 -0
  20. package/vendor/agent-cli/dist/src/artifacts/external-game-upload.d.ts +44 -0
  21. package/vendor/agent-cli/dist/src/artifacts/external-game-upload.d.ts.map +1 -0
  22. package/vendor/agent-cli/dist/src/artifacts/external-game-upload.js +106 -0
  23. package/vendor/agent-cli/dist/src/artifacts/external-game-upload.js.map +1 -0
  24. package/vendor/agent-cli/dist/src/index.d.ts +2 -0
  25. package/vendor/agent-cli/dist/src/index.d.ts.map +1 -1
  26. package/vendor/agent-cli/dist/src/index.js +2 -0
  27. package/vendor/agent-cli/dist/src/index.js.map +1 -1
package/README.md CHANGED
@@ -16,7 +16,7 @@ Requires Node.js 22.12 or newer with npm. Both engine contexts and project templ
16
16
  "--yes",
17
17
  "--prefer-online",
18
18
  "--registry=https://registry.npmjs.org/",
19
- "@craft_eco/craft-mcp@0.1.14"
19
+ "@craft_eco/craft-mcp@0.1.18"
20
20
  ],
21
21
  "env": {
22
22
  "CRAFT_WEB_URL": "https://test.craft.qq.com"
@@ -1,91 +1,53 @@
1
- import path from 'node:path';
2
- import { createHash } from 'node:crypto';
3
- import { crc32 } from 'node:zlib';
4
- import { lstat, mkdir, realpath, writeFile } from 'node:fs/promises';
5
- import { snapshotFiles } from '../preview/preview-snapshot.mjs';
6
-
7
- function checkedName(name) {
8
- const parts = name.split('/');
9
- if (parts.some(part => !part || part.startsWith('.') || /[\\:\x00-\x1f\x7f]/.test(part))) {
10
- throw new Error('Invalid draft snapshot file name');
11
- }
12
- const encoded = Buffer.from(name);
13
- if (encoded.length > 65535) throw new Error('Draft snapshot file name is too long');
14
- return encoded;
15
- }
16
-
17
- export async function freezeCheckedBuild(project, runDirectory, artifacts, signal) {
18
- const files = await snapshotFiles(project, artifacts);
19
- const output = path.join(runDirectory, 'dist');
20
- await mkdir(output, { mode: 0o700 });
21
- for (const [url, { data }] of files) {
22
- signal.throwIfAborted();
23
- const name = url.slice(1);
24
- checkedName(name);
25
- const target = path.join(output, ...name.split('/'));
26
- await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
27
- await writeFile(target, data, { flag: 'wx', mode: 0o600 });
28
- }
29
- return output;
30
- }
31
-
32
- // Store the verified bytes unchanged. Keeping headers and file buffers separate
33
- // lets the gateway receive a fixed-length stream without allocating a second ZIP.
34
- export function encodeDraftArchive(files) {
35
- const parts = [], central = [], names = new Set();
36
- let offset = 0, centralBytes = 0;
37
- for (const [url, { data }] of files) {
38
- const name = url.slice(1), key = name.toLowerCase(), encoded = checkedName(name);
39
- if (names.has(key)) throw new Error('Draft snapshot contains duplicate file names');
40
- names.add(key);
41
- const checksum = crc32(data);
42
- const local = Buffer.alloc(30);
43
- local.writeUInt32LE(0x04034b50, 0);
44
- local.writeUInt16LE(20, 4);
45
- local.writeUInt16LE(0x800, 6); // UTF-8 names.
46
- local.writeUInt16LE(0x21, 12); // 1980-01-01, stable across retries.
47
- local.writeUInt32LE(checksum, 14);
48
- local.writeUInt32LE(data.length, 18);
49
- local.writeUInt32LE(data.length, 22);
50
- local.writeUInt16LE(encoded.length, 26);
51
- const entry = Buffer.alloc(46);
52
- entry.writeUInt32LE(0x02014b50, 0);
53
- entry.writeUInt16LE(20, 4);
54
- local.copy(entry, 6, 4, 30);
55
- entry.writeUInt32LE(offset, 42);
56
- parts.push(local, encoded, data);
57
- central.push(entry, encoded);
58
- offset += local.length + encoded.length + data.length;
59
- centralBytes += entry.length + encoded.length;
60
- }
61
- const end = Buffer.alloc(22);
62
- end.writeUInt32LE(0x06054b50, 0);
63
- end.writeUInt16LE(names.size, 8);
64
- end.writeUInt16LE(names.size, 10);
65
- end.writeUInt32LE(centralBytes, 12);
66
- end.writeUInt32LE(offset, 16);
67
- const bytes = offset + centralBytes + end.length;
68
- if (bytes > 65 * 1024 * 1024) throw new Error('Draft ZIP exceeds the platform size limit');
69
- parts.push(...central, end);
70
- const hash = createHash('sha256');
71
- for (const part of parts) hash.update(part);
72
- return { parts, bytes, sha256: hash.digest('hex') };
73
- }
74
-
75
- export async function checkedDraftArchive(evidence, snapshotId, artifacts, signal) {
76
- if (typeof snapshotId !== 'string' || !/^[0-9a-f-]{36}$/.test(snapshotId)) {
77
- throw new Error('The check has no frozen build. Run craft_game_check again');
78
- }
79
- const root = await realpath(evidence);
80
- const runDirectory = path.join(root, snapshotId);
81
- if ((await lstat(runDirectory)).isSymbolicLink() || await realpath(runDirectory) !== runDirectory) {
82
- throw new Error('Invalid frozen build directory');
83
- }
84
- const frozen = artifacts.map(artifact => {
85
- checkedName(artifact.relativePath);
86
- return { ...artifact, path: path.join(runDirectory, 'dist', ...artifact.relativePath.split('/')) };
87
- });
88
- const files = await snapshotFiles(runDirectory, frozen);
89
- signal.throwIfAborted();
90
- return encodeDraftArchive(files);
91
- }
1
+ import path from 'node:path';
2
+ import { encodeExternalGameArchive } from '#craft-sdk';
3
+ import { lstat, mkdir, realpath, writeFile } from 'node:fs/promises';
4
+ import { snapshotFiles } from '../preview/preview-snapshot.mjs';
5
+
6
+ function checkedName(name) {
7
+ const parts = name.split('/');
8
+ if (parts.some(part => !part || part.startsWith('.') || /[\\:\x00-\x1f\x7f]/.test(part))) {
9
+ throw new Error('Invalid draft snapshot file name');
10
+ }
11
+ const encoded = Buffer.from(name);
12
+ if (encoded.length > 65535) throw new Error('Draft snapshot file name is too long');
13
+ return encoded;
14
+ }
15
+
16
+ export async function freezeCheckedBuild(project, runDirectory, artifacts, signal) {
17
+ const files = await snapshotFiles(project, artifacts);
18
+ const output = path.join(runDirectory, 'dist');
19
+ await mkdir(output, { mode: 0o700 });
20
+ for (const [url, { data }] of files) {
21
+ signal.throwIfAborted();
22
+ const name = url.slice(1);
23
+ checkedName(name);
24
+ const target = path.join(output, ...name.split('/'));
25
+ await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
26
+ await writeFile(target, data, { flag: 'wx', mode: 0o600 });
27
+ }
28
+ return output;
29
+ }
30
+
31
+ export async function checkedDraftFiles(evidence, snapshotId, artifacts, signal) {
32
+ if (typeof snapshotId !== 'string' || !/^[0-9a-f-]{36}$/.test(snapshotId)) {
33
+ throw new Error('The check has no frozen build. Run craft_game_check again');
34
+ }
35
+ const root = await realpath(evidence);
36
+ const runDirectory = path.join(root, snapshotId);
37
+ if ((await lstat(runDirectory)).isSymbolicLink() || await realpath(runDirectory) !== runDirectory) {
38
+ throw new Error('Invalid frozen build directory');
39
+ }
40
+ const frozen = artifacts.map(artifact => {
41
+ checkedName(artifact.relativePath);
42
+ return { ...artifact, path: path.join(runDirectory, 'dist', ...artifact.relativePath.split('/')) };
43
+ });
44
+ const files = await snapshotFiles(runDirectory, frozen);
45
+ signal.throwIfAborted();
46
+ return files;
47
+ }
48
+
49
+
50
+ export async function checkedDraftArchive(evidence,snapshotId,artifacts,signal) {
51
+ const files=await checkedDraftFiles(evidence,snapshotId,artifacts,signal);
52
+ return encodeExternalGameArchive(Array.from(files,([url,{ data }])=>[url.slice(1),data]),signal);
53
+ }
@@ -1,207 +1,207 @@
1
- import { checkedDraftArchive } from './draft-archive.mjs';
2
- import path from 'node:path';
3
- import { DraftBindings } from './draft-bindings.mjs';
4
- import { digest } from './request-store.mjs';
5
-
6
- function prepareInput(record) {
7
- const input = record.prepare_input ?? { client_request_id:record.request_id, engine:record.engine,
8
- title:record.name.slice(0,40), bytes:record.bytes, sha256:record.sha256 };
9
- if (input.client_request_id !== record.request_id || input.engine !== record.engine ||
10
- input.bytes !== record.bytes || input.sha256 !== record.sha256 ||
11
- Boolean(input.conversation_id) !== Boolean(input.expected_base_version_id)) throw new Error('Invalid saved draft prepare input');
12
- return input;
13
- }
14
-
15
- const terminal = record => ['draft_ready','expired'].includes(record.state);
16
-
17
- function view(record) {
18
- return { state:record.state, check_task_id:record.request_id, request_id:record.request_id,
19
- upload_id:record.upload_id, conversation_id:record.conversation_id, version_id:record.version_id,
20
- preview_path:record.preview_path, published:false,
21
- ...(record.external_manifest_sha256 ? { external_manifest_sha256:record.external_manifest_sha256 } : {}),
22
- next:record.state === 'draft_ready' ? 'Open the private draft preview in Craft with the same account.' :
23
- record.state === 'expired' ? 'Run a new game check and upload that result to start a new draft.' :
24
- 'Run craft_game_upload with the same check_task_id to resume this upload.' };
25
- }
26
-
27
- export class DraftUploads {
28
- constructor(platform, store, evidence, bindings) {
29
- this.platform = platform;
30
- this.store = store;
31
- this.evidence = evidence;
32
- this.bindings = bindings ?? new DraftBindings(path.join(path.dirname(store.directory),'draft-bindings'),store.workspace);
33
- }
34
-
35
- #scope(name,engine,owner) {
36
- return { workspace:this.store.workspace, name, engine, owner, platform:this.platform.base };
37
- }
38
-
39
- async #record(name, id, owner) {
40
- let record;
41
- try { record = await this.store.read(id); }
42
- catch (error) { if (error.code === 'ENOENT') return; throw error; }
43
- if (record.name !== name || record.owner !== owner || record.platform !== this.platform.base) {
44
- throw new Error('Draft upload belongs to a different project, account or platform');
45
- }
46
- return record;
47
- }
48
-
49
- async hasRequest(name, id, owner) { return Boolean(await this.#record(name,id,owner)); }
50
-
51
- async publicationSource(name, id, owner, signal) {
52
- const record = await this.#record(name,id,owner);
53
- if (!record) throw new Error('Upload this checked build before preparing publication');
54
- return { ...await this.status(name,id,owner,signal),archive_sha256:record.sha256,engine:record.engine };
55
- }
56
-
57
- async #accept(record, result) {
58
- if (record.upload_id !== undefined && record.upload_id !== result.upload_id) throw new Error('Craft changed the upload ID for this request');
59
- if (result.state === 'draft_ready' && (!result.conversation_id || !result.version_id ||
60
- (record.prepare_input?.conversation_id && record.prepare_input.conversation_id !== result.conversation_id))) {
61
- throw new Error('Craft returned a different draft project');
62
- }
63
- const updated = { ...record, ...result };
64
- await this.store.save(updated);
65
- return updated;
66
- }
67
-
68
- async #pending(scope, binding) {
69
- const saved = binding.pending;
70
- if (Object.entries(scope).some(([key,value])=>saved[key] !== value)) throw new Error('Invalid pending draft binding');
71
- const record = await this.#record(scope.name,saved.request_id,scope.owner) ?? saved;
72
- if (record.engine !== scope.engine || digest(prepareInput(record)) !== digest(prepareInput(saved))) {
73
- throw new Error('Pending draft request changed');
74
- }
75
- // Keep a complete pending receipt in the shared ledger so another profile can recover it.
76
- await this.store.save(record);
77
- return record;
78
- }
79
-
80
- async #finish(scope, binding, record) {
81
- if (binding.pending?.request_id !== record.request_id) throw new Error('Draft binding pending request changed');
82
- if (record.state === 'draft_ready') {
83
- const input = prepareInput(record);
84
- if (!binding.migration && (input.conversation_id !== binding.conversation_id ||
85
- input.expected_base_version_id !== binding.version_id)) throw new Error('Draft project base version changed');
86
- binding.conversation_id = record.conversation_id;
87
- binding.version_id = record.version_id;
88
- binding.last_request_id = record.request_id;
89
- delete binding.migration;
90
- }
91
- delete binding.pending;
92
- return this.bindings.save(scope,binding);
93
- }
94
-
95
- async #recover(record, request, signal) {
96
- if (terminal(record)) return record;
97
- signal?.throwIfAborted();
98
- record = await this.#accept(record,await (record.upload_id
99
- ? request('status',{ id:record.upload_id },signal)
100
- : request('prepare',{ input:prepareInput(record) },signal)));
101
- if (record.state === 'uploaded') {
102
- signal?.throwIfAborted();
103
- record = await this.#accept(record,await request('commit',{ id:record.upload_id },signal));
104
- }
105
- return record;
106
- }
107
-
108
- async #loadBinding(scope) {
109
- let binding = await this.bindings.read(scope);
110
- if (!binding) {
111
- const history = (await this.store.list()).filter(record=>
112
- Object.entries(scope).every(([key,value])=>record[key] === value) && record.state !== 'expired');
113
- if (history.some(record=>!Number.isFinite(Date.parse(record.created_at)))) throw new Error('Invalid draft upload history timestamp');
114
- history.sort((a,b)=>Date.parse(b.created_at)-Date.parse(a.created_at));
115
- if (history.some((record,index)=>index && Date.parse(record.created_at) === Date.parse(history[index-1].created_at))) {
116
- throw new Error('Ambiguous draft upload history; cannot choose the original project');
117
- }
118
- // Persist the migration queue as well: a crash or profile switch must not lose older receipts.
119
- binding = await this.bindings.save(scope,{ schema:1,...scope,migration:history });
120
- }
121
- return binding;
122
- }
123
-
124
- async #binding(scope, id, request, signal) {
125
- let binding = await this.#loadBinding(scope);
126
- for (;;) {
127
- if (!binding.pending && binding.migration?.length) {
128
- const record = binding.migration.shift();
129
- record.prepare_input = prepareInput(record);
130
- await this.store.save(record);
131
- binding.pending = record;
132
- await this.bindings.save(scope,binding);
133
- }
134
- if (!binding.pending) {
135
- if (binding.migration) { delete binding.migration; await this.bindings.save(scope,binding); }
136
- return binding;
137
- }
138
- const record = await this.#pending(scope,binding);
139
- if (record.request_id === id) return binding;
140
- const recovered = await this.#recover(record,request,signal);
141
- if (!terminal(recovered)) throw new Error(`Previous draft upload ${record.request_id} is unfinished; resume craft_game_upload with that check_task_id before uploading a new check`);
142
- binding = await this.#finish(scope,binding,recovered);
143
- }
144
- }
145
-
146
- async upload(check, owner, signal) {
147
- const { name, task_id:id, result } = check;
148
- const request = this.platform.draftSession(owner);
149
- let record = await this.#record(name,id,owner);
150
- if (record && record.engine !== result.engine) throw new Error('Draft upload engine changed');
151
- const scope = this.#scope(name,result.engine,owner);
152
- if (record && terminal(record)) {
153
- const binding = await this.#loadBinding(scope);
154
- if (binding?.pending?.request_id === id) await this.#finish(scope,binding,record);
155
- return view(record);
156
- }
157
- const archive = await checkedDraftArchive(this.evidence,result.snapshot_id,result.artifacts,signal);
158
- if (record && (record.sha256 !== archive.sha256 || record.bytes !== archive.bytes)) {
159
- throw new Error('Frozen build differs from the original draft upload');
160
- }
161
- let binding = await this.#binding(scope,id,request,signal);
162
- record = binding.pending ? await this.#pending(scope,binding) : record;
163
- if (record && (record.sha256 !== archive.sha256 || record.bytes !== archive.bytes)) {
164
- throw new Error('Frozen build differs from the original draft upload');
165
- }
166
- if (record && terminal(record)) {
167
- await this.#finish(scope,binding,record);
168
- return view(record);
169
- }
170
- const input = record ? prepareInput(record) : { client_request_id:id, engine:result.engine, title:name.slice(0,40),
171
- bytes:archive.bytes, sha256:archive.sha256, ...(binding.conversation_id
172
- ? { conversation_id:binding.conversation_id,expected_base_version_id:binding.version_id } : {}) };
173
- if (!binding.pending && (input.conversation_id !== binding.conversation_id || input.expected_base_version_id !== binding.version_id)) {
174
- throw new Error('Saved draft request targets an older project version; run a new game check');
175
- }
176
- record ??= await this.store.create({ request_id:id, ...scope, bytes:input.bytes, sha256:input.sha256,
177
- state:'preparing',prepare_input:input });
178
- record.prepare_input ??= input;
179
- // Save immutable target/base before any remote request, then make it recoverable across profiles.
180
- await this.store.save(record);
181
- binding.pending = record;
182
- await this.bindings.save(scope,binding);
183
- const run = async (kind, options) => {
184
- signal.throwIfAborted();
185
- record = await this.#accept(record,await request(kind,options,signal));
186
- };
187
- // The same check ID and archive digest are replayed even when a response was lost.
188
- await run('prepare',{ input });
189
- if (record.state === 'prepared') {
190
- await run('upload',{ id:record.upload_id, archive });
191
- if (!['uploaded','draft_ready'].includes(record.state)) throw new Error('Craft did not confirm the draft archive upload');
192
- }
193
- if (record.state === 'uploaded') {
194
- await run('commit',{ id:record.upload_id });
195
- if (record.state !== 'draft_ready') throw new Error('Craft did not finish the draft version');
196
- }
197
- if (terminal(record)) binding = await this.#finish(scope,binding,record);
198
- return view(record);
199
- }
200
-
201
- async status(name, id, owner, signal) {
202
- const record = await this.#record(name,id,owner);
203
- if (!record) return { state:'not_started', check_task_id:id, published:false };
204
- const remote = record.upload_id ? await this.platform.draftSession(owner)('status',{ id:record.upload_id },signal) : undefined;
205
- return view({ ...record, ...remote });
206
- }
207
- }
1
+ import { checkedDraftArchive } from './draft-archive.mjs';
2
+ import path from 'node:path';
3
+ import { DraftBindings } from './draft-bindings.mjs';
4
+ import { digest } from './request-store.mjs';
5
+
6
+ function prepareInput(record) {
7
+ const input = record.prepare_input ?? { client_request_id:record.request_id, engine:record.engine,
8
+ title:record.name.slice(0,40), bytes:record.bytes, sha256:record.sha256 };
9
+ if (input.client_request_id !== record.request_id || input.engine !== record.engine ||
10
+ input.bytes !== record.bytes || input.sha256 !== record.sha256 ||
11
+ Boolean(input.conversation_id) !== Boolean(input.expected_base_version_id)) throw new Error('Invalid saved draft prepare input');
12
+ return input;
13
+ }
14
+
15
+ const terminal = record => ['draft_ready','expired'].includes(record.state);
16
+
17
+ export function draftUploadView(record) {
18
+ return { state:record.state, check_task_id:record.request_id, request_id:record.request_id,
19
+ upload_id:record.upload_id, conversation_id:record.conversation_id, version_id:record.version_id,
20
+ published:false,
21
+ ...(record.external_manifest_sha256 ? { external_manifest_sha256:record.external_manifest_sha256 } : {}),
22
+ next:record.state === 'draft_ready' ? 'Private draft upload is complete and is not published. Use craft_game_deliver for the checked build and the IDE terminal to start its local preview.' :
23
+ record.state === 'expired' ? 'Run a new game check and upload that result to start a new draft.' :
24
+ 'Run craft_game_upload with the same check_task_id to resume this upload.' };
25
+ }
26
+
27
+ export class DraftUploads {
28
+ constructor(platform, store, evidence, bindings) {
29
+ this.platform = platform;
30
+ this.store = store;
31
+ this.evidence = evidence;
32
+ this.bindings = bindings ?? new DraftBindings(path.join(path.dirname(store.directory),'draft-bindings'),store.workspace);
33
+ }
34
+
35
+ #scope(name,engine,owner) {
36
+ return { workspace:this.store.workspace, name, engine, owner, platform:this.platform.base };
37
+ }
38
+
39
+ async #record(name, id, owner) {
40
+ let record;
41
+ try { record = await this.store.read(id); }
42
+ catch (error) { if (error.code === 'ENOENT') return; throw error; }
43
+ if (record.name !== name || record.owner !== owner || record.platform !== this.platform.base) {
44
+ throw new Error('Draft upload belongs to a different project, account or platform');
45
+ }
46
+ return record;
47
+ }
48
+
49
+ async hasRequest(name, id, owner) { return Boolean(await this.#record(name,id,owner)); }
50
+
51
+ async publicationSource(name, id, owner, signal) {
52
+ const record = await this.#record(name,id,owner);
53
+ if (!record) throw new Error('Upload this checked build before preparing publication');
54
+ return { ...await this.status(name,id,owner,signal),archive_sha256:record.sha256,engine:record.engine };
55
+ }
56
+
57
+ async #accept(record, result) {
58
+ if (record.upload_id !== undefined && record.upload_id !== result.upload_id) throw new Error('Craft changed the upload ID for this request');
59
+ if (result.state === 'draft_ready' && (!result.conversation_id || !result.version_id ||
60
+ (record.prepare_input?.conversation_id && record.prepare_input.conversation_id !== result.conversation_id))) {
61
+ throw new Error('Craft returned a different draft project');
62
+ }
63
+ const updated = { ...record, ...result };
64
+ await this.store.save(updated);
65
+ return updated;
66
+ }
67
+
68
+ async #pending(scope, binding) {
69
+ const saved = binding.pending;
70
+ if (Object.entries(scope).some(([key,value])=>saved[key] !== value)) throw new Error('Invalid pending draft binding');
71
+ const record = await this.#record(scope.name,saved.request_id,scope.owner) ?? saved;
72
+ if (record.engine !== scope.engine || digest(prepareInput(record)) !== digest(prepareInput(saved))) {
73
+ throw new Error('Pending draft request changed');
74
+ }
75
+ // Keep a complete pending receipt in the shared ledger so another profile can recover it.
76
+ await this.store.save(record);
77
+ return record;
78
+ }
79
+
80
+ async #finish(scope, binding, record) {
81
+ if (binding.pending?.request_id !== record.request_id) throw new Error('Draft binding pending request changed');
82
+ if (record.state === 'draft_ready') {
83
+ const input = prepareInput(record);
84
+ if (!binding.migration && (input.conversation_id !== binding.conversation_id ||
85
+ input.expected_base_version_id !== binding.version_id)) throw new Error('Draft project base version changed');
86
+ binding.conversation_id = record.conversation_id;
87
+ binding.version_id = record.version_id;
88
+ binding.last_request_id = record.request_id;
89
+ delete binding.migration;
90
+ }
91
+ delete binding.pending;
92
+ return this.bindings.save(scope,binding);
93
+ }
94
+
95
+ async #recover(record, request, signal) {
96
+ if (terminal(record)) return record;
97
+ signal?.throwIfAborted();
98
+ record = await this.#accept(record,await (record.upload_id
99
+ ? request('status',{ id:record.upload_id },signal)
100
+ : request('prepare',{ input:prepareInput(record) },signal)));
101
+ if (record.state === 'uploaded') {
102
+ signal?.throwIfAborted();
103
+ record = await this.#accept(record,await request('commit',{ id:record.upload_id },signal));
104
+ }
105
+ return record;
106
+ }
107
+
108
+ async #loadBinding(scope) {
109
+ let binding = await this.bindings.read(scope);
110
+ if (!binding) {
111
+ const history = (await this.store.list()).filter(record=>
112
+ Object.entries(scope).every(([key,value])=>record[key] === value) && record.state !== 'expired');
113
+ if (history.some(record=>!Number.isFinite(Date.parse(record.created_at)))) throw new Error('Invalid draft upload history timestamp');
114
+ history.sort((a,b)=>Date.parse(b.created_at)-Date.parse(a.created_at));
115
+ if (history.some((record,index)=>index && Date.parse(record.created_at) === Date.parse(history[index-1].created_at))) {
116
+ throw new Error('Ambiguous draft upload history; cannot choose the original project');
117
+ }
118
+ // Persist the migration queue as well: a crash or profile switch must not lose older receipts.
119
+ binding = await this.bindings.save(scope,{ schema:1,...scope,migration:history });
120
+ }
121
+ return binding;
122
+ }
123
+
124
+ async #binding(scope, id, request, signal) {
125
+ let binding = await this.#loadBinding(scope);
126
+ for (;;) {
127
+ if (!binding.pending && binding.migration?.length) {
128
+ const record = binding.migration.shift();
129
+ record.prepare_input = prepareInput(record);
130
+ await this.store.save(record);
131
+ binding.pending = record;
132
+ await this.bindings.save(scope,binding);
133
+ }
134
+ if (!binding.pending) {
135
+ if (binding.migration) { delete binding.migration; await this.bindings.save(scope,binding); }
136
+ return binding;
137
+ }
138
+ const record = await this.#pending(scope,binding);
139
+ if (record.request_id === id) return binding;
140
+ const recovered = await this.#recover(record,request,signal);
141
+ if (!terminal(recovered)) throw new Error(`Previous draft upload ${record.request_id} is unfinished; resume craft_game_upload with that check_task_id before uploading a new check`);
142
+ binding = await this.#finish(scope,binding,recovered);
143
+ }
144
+ }
145
+
146
+ async upload(check, owner, signal) {
147
+ const { name, task_id:id, result } = check;
148
+ const request = this.platform.draftSession(owner);
149
+ let record = await this.#record(name,id,owner);
150
+ if (record && record.engine !== result.engine) throw new Error('Draft upload engine changed');
151
+ const scope = this.#scope(name,result.engine,owner);
152
+ if (record && terminal(record)) {
153
+ const binding = await this.#loadBinding(scope);
154
+ if (binding?.pending?.request_id === id) await this.#finish(scope,binding,record);
155
+ return draftUploadView(record);
156
+ }
157
+ const archive = await checkedDraftArchive(this.evidence,result.snapshot_id,result.artifacts,signal);
158
+ if (record && (record.sha256 !== archive.sha256 || record.bytes !== archive.bytes)) {
159
+ throw new Error('Frozen build differs from the original draft upload');
160
+ }
161
+ let binding = await this.#binding(scope,id,request,signal);
162
+ record = binding.pending ? await this.#pending(scope,binding) : record;
163
+ if (record && (record.sha256 !== archive.sha256 || record.bytes !== archive.bytes)) {
164
+ throw new Error('Frozen build differs from the original draft upload');
165
+ }
166
+ if (record && terminal(record)) {
167
+ await this.#finish(scope,binding,record);
168
+ return draftUploadView(record);
169
+ }
170
+ const input = record ? prepareInput(record) : { client_request_id:id, engine:result.engine, title:name.slice(0,40),
171
+ bytes:archive.bytes, sha256:archive.sha256, ...(binding.conversation_id
172
+ ? { conversation_id:binding.conversation_id,expected_base_version_id:binding.version_id } : {}) };
173
+ if (!binding.pending && (input.conversation_id !== binding.conversation_id || input.expected_base_version_id !== binding.version_id)) {
174
+ throw new Error('Saved draft request targets an older project version; run a new game check');
175
+ }
176
+ record ??= await this.store.create({ request_id:id, ...scope, bytes:input.bytes, sha256:input.sha256,
177
+ state:'preparing',prepare_input:input });
178
+ record.prepare_input ??= input;
179
+ // Save immutable target/base before any remote request, then make it recoverable across profiles.
180
+ await this.store.save(record);
181
+ binding.pending = record;
182
+ await this.bindings.save(scope,binding);
183
+ const run = async (kind, options) => {
184
+ signal.throwIfAborted();
185
+ record = await this.#accept(record,await request(kind,options,signal));
186
+ };
187
+ // The same check ID and archive digest are replayed even when a response was lost.
188
+ await run('prepare',{ input });
189
+ if (record.state === 'prepared') {
190
+ await run('upload',{ id:record.upload_id, archive });
191
+ if (!['uploaded','draft_ready'].includes(record.state)) throw new Error('Craft did not confirm the draft archive upload');
192
+ }
193
+ if (record.state === 'uploaded') {
194
+ await run('commit',{ id:record.upload_id });
195
+ if (record.state !== 'draft_ready') throw new Error('Craft did not finish the draft version');
196
+ }
197
+ if (terminal(record)) binding = await this.#finish(scope,binding,record);
198
+ return draftUploadView(record);
199
+ }
200
+
201
+ async status(name, id, owner, signal) {
202
+ const record = await this.#record(name,id,owner);
203
+ if (!record) return { state:'not_started', check_task_id:id, published:false };
204
+ const remote = record.upload_id ? await this.platform.draftSession(owner)('status',{ id:record.upload_id },signal) : undefined;
205
+ return draftUploadView({ ...record, ...remote });
206
+ }
207
+ }
@@ -37,8 +37,9 @@ export class Publications {
37
37
 
38
38
  #directory(record) { return path.join(this.store.directory,record.request_id); }
39
39
 
40
- async prepare(check, project, input, owner, signal) {
40
+ async prepare(check, project, input, owner, signal, stagedCover) {
41
41
  const materials = publicationMaterials(input);
42
+ if (stagedCover && materials.cover_path) throw new Error('Choose one publication cover source');
42
43
  const source = await this.drafts.publicationSource(check.name,check.task_id,owner,signal);
43
44
  if (source.state !== 'draft_ready' || !/^[0-9a-f]{64}$/.test(source.external_manifest_sha256 ?? '')) throw new Error('Upload this checked build with craft_game_upload before preparing publication; the Web runtime must return its manifest SHA');
44
45
  const existing = await this.platform.publicationSession(owner)('status',{ version_id:source.version_id },signal);
@@ -52,7 +53,8 @@ export class Publications {
52
53
  const id = randomUUID(), directory = path.join(this.store.directory,id);
53
54
  await mkdir(directory,{ mode:0o700 });
54
55
  const images = [];
55
- if (materials.cover_path) images.push(await copyMaterial(project,materials.cover_path,directory,'cover','cover'));
56
+ if (stagedCover) images.push(await copyMaterial(stagedCover.directory,stagedCover.file,directory,'cover','cover',stagedCover));
57
+ else if (materials.cover_path) images.push(await copyMaterial(project,materials.cover_path,directory,'cover','cover'));
56
58
  else {
57
59
  const file = capture.screenshots[0];
58
60
  images.push(await copyMaterial(path.dirname(file),path.basename(file),directory,'cover','cover',capture.screenshot_files?.[0]));