@chrona-city/ugc-kit 1.5.11 → 1.5.13

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 (39) hide show
  1. package/README.md +63 -0
  2. package/docs/harness-onboarding.md +44 -3
  3. package/docs/meshy.md +13 -0
  4. package/docs/npm-creator.md +1 -1
  5. package/docs/runtime-download.md +34 -0
  6. package/lib/creator-api.mjs +80 -9
  7. package/lib/creator-cli.mjs +13 -3
  8. package/lib/creator-contribution.mjs +1 -1
  9. package/lib/creator-install.mjs +48 -5
  10. package/lib/creator-mcp.mjs +1 -0
  11. package/lib/creator-onboarding.mjs +3 -2
  12. package/lib/creator-platform.mjs +4 -2
  13. package/lib/creator-project-update.mjs +4 -1
  14. package/lib/creator-session.mjs +11 -5
  15. package/lib/creator-toolchain-compat.mjs +3 -0
  16. package/lib/meshy-cli.mjs +23 -0
  17. package/lib/meshy-store.mjs +33 -10
  18. package/node_modules/pngjs/CHANGELOG.md +128 -0
  19. package/package.json +1 -2
  20. package/runtime-catalog.json +16 -16
  21. package/node_modules/@esbuild/darwin-arm64/README.md +0 -3
  22. package/node_modules/@esbuild/darwin-arm64/bin/esbuild +0 -0
  23. package/node_modules/@esbuild/darwin-arm64/package.json +0 -20
  24. package/node_modules/@esbuild/darwin-x64/README.md +0 -3
  25. package/node_modules/@esbuild/darwin-x64/bin/esbuild +0 -0
  26. package/node_modules/@esbuild/darwin-x64/package.json +0 -20
  27. package/node_modules/@esbuild/linux-arm64/README.md +0 -3
  28. package/node_modules/@esbuild/linux-arm64/bin/esbuild +0 -0
  29. package/node_modules/@esbuild/linux-arm64/package.json +0 -20
  30. package/node_modules/@esbuild/linux-x64/README.md +0 -3
  31. package/node_modules/@esbuild/linux-x64/bin/esbuild +0 -0
  32. package/node_modules/@esbuild/linux-x64/package.json +0 -20
  33. package/node_modules/esbuild/LICENSE.md +0 -21
  34. package/node_modules/esbuild/README.md +0 -3
  35. package/node_modules/esbuild/bin/esbuild +0 -223
  36. package/node_modules/esbuild/install.js +0 -289
  37. package/node_modules/esbuild/lib/main.d.ts +0 -716
  38. package/node_modules/esbuild/lib/main.js +0 -2242
  39. package/node_modules/esbuild/package.json +0 -49
package/README.md CHANGED
@@ -199,3 +199,66 @@ npm run capabilities -- --id combat.melee
199
199
  The query never grants a Capability. Build-time resolution generates `capabilities.lock.json`, `effective-budgets.json`, and a network Profile lock from the platform-managed Registry. Unknown required capabilities return `needs_capability`; optional capabilities must terminate in an explicit disable or cosmetic-only fallback.
200
200
 
201
201
  A missing required Capability may include a semantic proposal under `content/proposals/`, validated by the locked wiring contract. Platform Node/Web integration uses the separate internal Skill under `platform/`; that directory is never copied into generated creator projects.
202
+
203
+ ### Resume existing release materials
204
+
205
+ `npm run verify:npm-package -- --inspect-release INPUT` is read-only.
206
+ `--continue-release INPUT` resumes only verified missing local catalog/portable
207
+ steps; it never clears partial output, creates a Tag, publishes npm or writes a
208
+ cloud target. The input references `pairingFile`, `catalogFile`, `finalDirectory`,
209
+ `outputDirectory` and `releaseProfile` (`city` or `world`). Optional `sourceRoot`
210
+ selects the clean fixed source of the final package; it is distinct from the
211
+ tool running the inspection. Optional `runtimeMaterials` uses the existing
212
+ `{bundleDirectory, manifestSha256}` closed resolver. Historical material never
213
+ falls back to files on the current host.
214
+
215
+ An optional `catalogSetInputFile` is the original catalog-set input. Inspection
216
+ must match the requested bytes or the proven Producer baseline; only the
217
+ original CAS Writer performs a missing update. Commit the resulting common
218
+ source before final packaging. An unknown catalog state does not authorize a
219
+ retry. Missing final packages and Tag/finalization return their existing formal
220
+ entry as the next operation; this first slice does not execute those stages.
221
+
222
+ For a sealed final package, continuation derives the profile lock from
223
+ `finalDirectory/profile-package-lock.json`, calls the original export with the
224
+ real final result, then imports into `outputDirectory/final-imported`. The export
225
+ is `outputDirectory/final-portable`, unless the supplied closed bundle already
226
+ contains the exact expected final material. Complete outputs are reverified and
227
+ reused. Partial, changed or locked outputs are retained and rejected, not deleted
228
+ or overwritten. A local-complete result is **not** public-consumption evidence:
229
+ `recommendationReady` stays false until actual final-package download and run
230
+ have independently passed. Existing published archives and Runtime reports keep
231
+ their original identities.
232
+
233
+ Runtime reuse first verifies each complete profile lock body against its exact
234
+ evidence and package identity. Only execution-dependency comparison excludes the
235
+ two root carrier versions and `packages[""].bundleDependencies` (archive
236
+ packaging). Dependency entries, versions, URLs, integrity, optional/OS/CPU fields,
237
+ the authoritative source closure and original payload/report pins remain exact.
238
+ A packaging projection is never a new Runtime execution or a changed old proof.
239
+
240
+ To explicitly continue the **public consumer** stage, add
241
+ `"publicConsumption": { "npmCache": "/absolute/existing/npm-cache" }` to the
242
+ same input. Inspection is still read-only. Continuation derives the original
243
+ reference snapshot from pairing and the trusted URLs from the profile/catalog;
244
+ it accepts no caller URL, content identity or account override. It downloads
245
+ both immutable Runtime families with full byte/hash and archive checks before
246
+ requesting final metadata or the exact sealed tar. It then projects the existing
247
+ fixed platform npm cache using the original Writer, installs that downloaded tar,
248
+ checks caller identity/default Origin/catalog/native transform, and invokes the
249
+ installed Kit's original offline isolated `test` Reader. This explicit action
250
+ needs permission for those public GETs and the local QA Runtime/loopback test;
251
+ it never authorizes an account, uploads content or calls a model.
252
+
253
+ The generated `public-consumption/result.json` retains the exact artifact and
254
+ target identities, original test cleanup, request order and installed inventory.
255
+ Complete matching output is rechecked without rerunning; partial/failed output
256
+ is preserved with its first phase/code and cannot be blindly replayed. The
257
+ inspect command remains the safe next action, not deleting the directory.
258
+ Test transports or inert execution adapters keep both public/recommendation
259
+ flags false. Only the real HTTPS/owned installed test may make this artifact
260
+ eligible for an **explicitly approved** npm/Web handoff. npm publication,
261
+ registry readback, website deployment/current-alias verification and ordinary
262
+ user behavior stay separate: the returned handoff states never claim those
263
+ operations happened and never execute publish or cloud commands. A local
264
+ tarball, HEAD/200, another Kit or an old Host report is not this evidence.
@@ -65,6 +65,15 @@ still apply. A platform-provided archive is an alternative only when its
65
65
  actual release metadata and immutable bytes are verified; old IP aliases are
66
66
  historical distribution addresses, not the default for a new city installation.
67
67
 
68
+ esbuild is an exact npm dependency, not a set of bundled desktop binaries. npm
69
+ selects its official optional dependency for the actual installation platform.
70
+ The persistent installer first uses the existing cache offline; only an explicit
71
+ cache miss enables the original registry download path, within the same total
72
+ installation budget. An unknown, cancelled or damaged-cache failure is not
73
+ retried as a download. A real native transform must pass before registration;
74
+ an optional package silently omitted by npm does not mean the tool is ready.
75
+ This dependency check does not expand the Runtime's supported targets.
76
+
68
77
  Run `chrona init` from the selected project directory. The installed package's
69
78
  `creator-release.json` supplies official release defaults. The CLI checks the
70
79
  current release metadata against its immutable metadata and archive bytes before
@@ -120,13 +129,45 @@ Read `uploadPreflight`: source upload needs `projects:read`, `source:read` and
120
129
  `submissions:write`. A contribution uses the existing separate
121
130
  `contributions:write` scope. Missing scopes require an explicit new authorization
122
131
  in a separate private session directory; preserve the old session. Do not edit
123
- saved bindings, revoke it automatically or copy browser credentials. Expired,
124
- revoked or uncertain authorization returns `CREATOR_SESSION_RENEWAL_REQUIRED`;
125
- preserve its record and use the supported explicit continuation. Authorization
132
+ saved bindings, revoke it automatically or copy browser credentials. Platform
133
+ expiry timestamps are not compared with the device clock; the platform still
134
+ enforces expiry and revocation. An uncertain or unusable saved authorization
135
+ requires explicit continuation (`CREATOR_SESSION_RENEWAL_REQUIRED`); platform
136
+ rejections retain their specific error. Preserve the record, and do not retry an
137
+ unknown token exchange automatically. Authorization
126
138
  does not grant material entitlement, candidate acceptance or publication rights.
127
139
 
128
140
  ## Create and edit the selected work
129
141
 
142
+ ### World Agent personal model sign-in is separate
143
+
144
+ Use the existing Studio model settings for the selected World and the user's
145
+ own account. The versioned platform model-auth operation binds the original
146
+ profile ID, profile revision and request ID; its start, read and cancel are not
147
+ project upload tools. This Kit's upload authorization and managed Job transport
148
+ do not grant model configuration permission. Do not copy a browser session into
149
+ the CLI, add a scope locally, or send a project upload credential to Studio's
150
+ ordinary account endpoints. No local Kit sign-in command or MCP model-login tool
151
+ is claimed by this source change.
152
+
153
+ The current Codex device-code interaction belongs only in the user-controlled
154
+ official page and its trusted UI. Do not put its one-time code, raw native
155
+ output or tokens into model chat, MCP arguments/results, logs or project files.
156
+ Approval happens at the official site; there is no code-response action to
157
+ invent. Claude-specific interaction requires its own supported supplier; the
158
+ existing explicit manual Claude SDK route remains available without sending
159
+ tokens through model chat. An unavailable approved supplier must not fall back
160
+ to an API key, public client ID or platform-paid identity.
161
+
162
+ Keep authentication, profile saving, explicit verification, activation and an
163
+ actual model turn separate. `authenticated` does not prove the other steps or
164
+ quota. If the outcome or writer exit is unknown, read the same original
165
+ profile/revision/request operation; do not create a replacement login or assume
166
+ cancellation revoked credentials. Historical operation status and its cleanup
167
+ remain distinct from the currently selected model or Job engine.
168
+
169
+ ### Continue creation with the selected project
170
+
130
171
  Start with `list_ugc_projects`. `projectName: "."` means only the configured
131
172
  directory; discovery reads it and its direct child projects, not an entire home
132
173
  tree. Ask the user to choose when there are multiple projects. An empty directory
package/docs/meshy.md CHANGED
@@ -22,6 +22,19 @@ settings are preserved. A replacement is read on the next call; installs and
22
22
  tool upgrades do not delete the user configuration. Removal deletes the local
23
23
  entry, not the Meshy account key. Windows storage is not verified or enabled.
24
24
 
25
+ For unsafe storage, the first error identifies the directory, configuration,
26
+ credentials or local-state object, its observed type/owner/permissions and the
27
+ expected boundary. In your own terminal, `chrona meshy status` includes the
28
+ exact local object. Only an owned ordinary object's permission error includes a
29
+ manual, single-object `chmod` suggestion. Nothing applies it automatically;
30
+ never use recursive chmod, replace a key, or follow a link to bypass a refusal.
31
+ After reviewing and repairing that object yourself, repeat status; existing
32
+ credentials and unrelated settings remain intact. Wrong owner, links, repository
33
+ location and access failures require inspecting the original location instead.
34
+ MCP receives only finite object labels and observations, not local paths, Key
35
+ contents or a terminal command containing a path. Owner-only read permissions
36
+ are preserved; status does not demand write permission or rewrite valid files.
37
+
25
38
  After explicit user opt-in and an actual generation request, the Agent uses
26
39
  `create_meshy_asset` with a stable operationId and consent=true. These tools spend
27
40
  the creator's own Meshy credits. Saving a key does not authorize extra variants.
@@ -220,7 +220,7 @@ Static validate never imports creator JavaScript. Repair its structured errors a
220
220
 
221
221
  ### Upload authorization preflight
222
222
 
223
- The upload operation needs `source:read` to inspect/resume blobs, `submissions:write` to submit and `projects:read` for live platform preflight. `projects:create` replaces none of these scopes. The current candidate checks session expiry, fixed Origin, selected project scope and upload scopes before scanning the content tree. Missing scopes return `CREATOR_SESSION_SCOPE_REQUIRED` with `requiredScopes` and `missingScopes`; a different project grant returns `CREATOR_SESSION_PROJECT_MISMATCH`. These checks grant nothing and do not replace the server's current membership, source eligibility or authorization checks.
223
+ The upload operation needs `source:read` to inspect/resume blobs, `submissions:write` to submit and `projects:read` for live platform preflight. `projects:create` replaces none of these scopes. The Kit checks the saved credential structure, fixed Origin, selected project scope and upload scopes before scanning the content tree. Expiry timestamps belong to the platform clock: the Kit preserves them but does not reject authorization, exchange, upload or snapshot reads by comparing them with the device clock. The platform enforces actual expiry, revocation, current membership and eligibility on each operation. Missing scopes return `CREATOR_SESSION_SCOPE_REQUIRED` with `requiredScopes` and `missingScopes`; a different project grant returns `CREATOR_SESSION_PROJECT_MISMATCH`. Local checks grant nothing and never extend an authorization.
224
224
 
225
225
  Read `uploadPreflight` in `auth-status` or MCP authorization results, including a reused `authorized` session. `scope-ready` means only that the local session contains the upload scopes; it is not permission to use every project or proof of publication. For `missing-scopes`, preserve the old session and explicitly use `login` with a new private session directory, the same trusted platform Origin, the intended `--project-id` and `--scopes source:read,submissions:write,projects:read`; complete normal browser approval and `login-complete`, then submit through that new session. Add other scopes only for intended operations. A project-bound grant cannot create new projects. Do not edit the existing session or automatically log it out. Repointing an existing MCP registration requires explicit configuration resolution; the tool never silently replaces it. Earlier fixed archives do not acquire this preflight without a separately installed candidate.
226
226
 
@@ -2,6 +2,15 @@
2
2
 
3
3
  ## Release-only Document payload reuse
4
4
 
5
+ A verified reuse delivery may be the next release's declaration predecessor.
6
+ Its complete pinned Producer, proof, manifests and profile locks must be present
7
+ in the closed material graph. New declarations preserve every verified previous
8
+ content row and add only the genuine current reference. Execution remains bound
9
+ to the original normal delivery, Producer, source lock, ZIP, actual targets and
10
+ reports; the predecessor is not a new execution. `newExecutionVerified` stays
11
+ `false`. Missing mappings, changed inputs and predecessor cycles reject without
12
+ host-path fallback. The original direct-normal route remains supported.
13
+
5
14
  The internal release tooling can consume a distinct `clients-runtime-reuse-delivery`
6
15
  with `status: static-verified` and `newExecutionVerified: false`. This is not an
7
16
  execution result or permission to reuse an arbitrary Runtime. The Kit rechecks the
@@ -16,6 +25,15 @@ current digest remains in the complete Producer evidence; the Clients Writer
16
25
  also verifies this leaf in the fixed current checkout. Compiler, SDK, contracts,
17
26
  policies, installed toolchain and runtime/host dependencies remain protected.
18
27
 
28
+ Scoped patch reuse uses the existing versioned companion execution selector.
29
+ Both actual profile lock bodies are bound to their own Producer evidence; only
30
+ `version` and `packages[""].version` are excluded from dependency comparison.
31
+ All dependency/SRI/resolved fields remain exact. The reuse output retains
32
+ `current-profile-package-lock.json` and `baseline-profile-package-lock.json`;
33
+ portable material carries these two explicit roles without new delivery fields
34
+ or host-path fallback. The report target remains the original observed machine,
35
+ not the manifest's support declarations.
36
+
19
37
  Catalog writing binds three separate sources: the immutable internal Producer,
20
38
  the current catalog writer, and the later final package commit. Only a verified
21
39
  reuse delivery can use a successor writer with the same protected execution
@@ -40,6 +58,17 @@ token, arbitrary lookup or fallback to the original host. Corruption, missing ro
40
58
  unknown aliases, links and unregistered paths reject. Legacy deliveries retain
41
59
  their original path and do not accept this resolver.
42
60
 
61
+ `--prepare-runtime-catalog INPUT` and `--export-runtime-materials INPUT` also
62
+ accept `--runtime-materials ABSOLUTE_MATERIAL_BUNDLE_JSON`. Their JSON input
63
+ keys are unchanged. For a newly supplied reuse Producer/delivery, only that
64
+ explicit new subgraph is read locally; its historical baseline stays within the
65
+ validated bundle. Missing historical mappings never fall back to the host.
66
+ The original two-argument import CLI and closed inventory checks are unchanged.
67
+ The catalog-set install/inspect CLI accepts the same option with an already
68
+ complete bundle. It resolves only the selected pairing's pinned subgraph; the
69
+ local input, current catalog, unselected profiles and original CAS/source gates
70
+ retain their existing boundaries.
71
+
43
72
  For a final package or its later finalization from imported reuse material, the
44
73
  existing release command accepts `--runtime-materials ABSOLUTE_MATERIAL_BUNDLE_JSON`
45
74
  in addition to its normal pairing/finalization input. The bundle inventory is
@@ -58,6 +87,11 @@ Producer/delivery/manifest/target checks before the catalog is combined. Both
58
87
  must bind the same release source, version, environment and complete toolchain;
59
88
  the additional delivery is a normal Producer delivery, not a borrowed Document
60
89
  companion or payload-reuse proof. No snapshot or content identity is converted.
90
+ An explicitly verified Document patch-reuse delivery can instead retain the
91
+ normal static Producer from its exact execution baseline. Its package, content,
92
+ reports and version keep their original identities. The new final carrier still
93
+ requires the same execution closure and complete verified dependency tree; an
94
+ unrelated historical Producer or a new static execution cannot be inferred.
61
95
  The shared release binding describes the two internal Kit packages, not a
62
96
  requirement for historical projects to adopt a new identity. Every historical
63
97
  content tuple still needs genuine compatibility and execution evidence; a new
@@ -39,6 +39,52 @@ const previewStates = new Map([
39
39
  const exact = (value, keys) => value && typeof value === 'object' && !Array.isArray(value)
40
40
  && Object.keys(value).sort().join(',') === [...keys].sort().join(',');
41
41
 
42
+ const modelConnectPurpose = 'claude-sdk-setup-token';
43
+ const uuid = value => typeof value === 'string' && /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/.test(value);
44
+ const modelConnectRequestKeys = ['deviceName', 'worldId', 'projectId', 'profileId', 'expectedRevision', 'model', 'name'];
45
+ const text = (value, max) => typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= max
46
+ && !/[\u0000\r\n]/.test(value) && value.trim() === value;
47
+ function validModelConnectRequest(value) {
48
+ return exact(value, modelConnectRequestKeys) && text(value.deviceName, 80) && uuid(value.worldId) && id(value.projectId)
49
+ && (value.profileId === null && value.expectedRevision === null || uuid(value.profileId) && uuid(value.expectedRevision))
50
+ && text(value.model, 150) && typeof value.name === 'string' && value.name.trim().length > 0
51
+ && Buffer.byteLength(value.name) <= 320;
52
+ }
53
+
54
+ // Internal purpose-specific proof, never an upload credential or Job binding.
55
+ export function validateCreatorModelConnectPending(pending, origin) {
56
+ if (!exact(pending, ['origin', 'connectId', 'codeVerifier', 'request']) || pending.origin !== origin
57
+ || !uuid(pending.connectId) || typeof pending.codeVerifier !== 'string'
58
+ || !/^[A-Za-z0-9._~-]{43,128}$/.test(pending.codeVerifier) || !validModelConnectRequest(pending.request))
59
+ fail('INVALID_AUTHORIZATION_SESSION');
60
+ return pending;
61
+ }
62
+
63
+ export function readCreatorModelConnectResult(data, { origin, connectId, request, accountId } = {}) {
64
+ const binding = data?.binding;
65
+ if (!uuid(connectId) || !validModelConnectRequest(request)
66
+ || !exact(data, ['connectId', 'purpose', 'status', 'expiresAtMs', 'binding', 'saved', 'errorCode', 'next'])
67
+ || data.connectId !== connectId || data.purpose !== modelConnectPurpose || !positiveInteger(data.expiresAtMs)
68
+ || !exact(binding, ['accountId', 'appOrigin', ...modelConnectRequestKeys]) || binding.appOrigin !== origin
69
+ || modelConnectRequestKeys.some(key => binding[key] !== request[key])
70
+ || !(binding.accountId === null || uuid(binding.accountId))
71
+ || accountId !== undefined && binding.accountId !== accountId) fail('INVALID_CREATOR_RESPONSE');
72
+ const next = { pending: 'approve', approved: 'generate-once', denied: 'none', cancelled: 'none', expired: 'none',
73
+ saved: 'done', unknown: 'read-original' };
74
+ if (!Object.hasOwn(next, data.status) || data.next !== next[data.status]
75
+ || (['approved', 'saved', 'unknown'].includes(data.status) && !uuid(binding.accountId))
76
+ || data.status === 'pending' && binding.accountId !== null
77
+ || data.errorCode !== (data.status === 'unknown' ? 'CREATOR_AGENT_AUTH_OUTCOME_UNKNOWN' : null)) fail('INVALID_CREATOR_RESPONSE');
78
+ if (data.status === 'saved') {
79
+ if (!exact(data.saved, ['profileId', 'revision', 'verificationStarted', 'activationRequested'])
80
+ || !uuid(data.saved.profileId) || !uuid(data.saved.revision)
81
+ || data.saved.verificationStarted !== false || data.saved.activationRequested !== false
82
+ || request.profileId !== null && data.saved.profileId !== request.profileId) fail('INVALID_CREATOR_RESPONSE');
83
+ } else if (data.saved !== null) fail('INVALID_CREATOR_RESPONSE');
84
+ // Expiry belongs to the server clock. No device Date.now qualification gate.
85
+ return structuredClone(data);
86
+ }
87
+
42
88
  // Platform technical-preview contract; omission keeps the server's 900s default.
43
89
  export function normalizeCreatorPreviewRequest(payload) {
44
90
  const lifetime = Object.hasOwn(payload ?? {}, 'lifetimeSeconds');
@@ -270,8 +316,8 @@ function creatorApi({ origin, allowLocalHttp = false, fetchImpl = globalThis.fet
270
316
  if (signal?.aborted) fail('CREATOR_REQUEST_CANCELLED');
271
317
  if (operationAdapter && credential !== undefined) fail('INVALID_CREATOR_CREDENTIAL');
272
318
  if (!operationAdapter && (route.startsWith('/projects') || route.startsWith('/terminal/')) && credential === undefined) fail('INVALID_CREATOR_CREDENTIAL');
273
- if (!operationAdapter && credential !== undefined && (!credential || credential.origin !== platform || !Number.isSafeInteger(credential.expiresAtMs)
274
- || credential.expiresAtMs <= Date.now() || !/^ct_[a-f0-9]{32}\.[a-f0-9]{64}$/.test(credential.accessToken ?? ''))) fail('INVALID_CREATOR_CREDENTIAL');
319
+ if (!operationAdapter && credential !== undefined && (!credential || credential.origin !== platform || !positiveInteger(credential.expiresAtMs)
320
+ || !/^ct_[a-f0-9]{32}\.[a-f0-9]{64}$/.test(credential.accessToken ?? ''))) fail('INVALID_CREATOR_CREDENTIAL');
275
321
  const encoded = body === undefined ? undefined : JSON.stringify(body);
276
322
  if (encoded && Buffer.byteLength(encoded) > bodyLimit) fail('CREATOR_REQUEST_TOO_LARGE');
277
323
  let response, payload;
@@ -373,25 +419,50 @@ function creatorApi({ origin, allowLocalHttp = false, fetchImpl = globalThis.fet
373
419
  const codeVerifier = randomBytes(32).toString('base64url');
374
420
  const data = await request('POST', '/authorizations', { body: { deviceName, scopes: [...requestedScopes],
375
421
  codeChallenge: createHash('sha256').update(codeVerifier).digest('base64url'), codeChallengeMethod: 'S256', ...(projectId ? { projectId } : {}) }, signal });
376
- if (!id(data.authorizationId) || data.status !== 'pending' || !Number.isSafeInteger(data.expiresAtMs)
377
- || data.expiresAtMs <= Date.now() || data.expiresAtMs > Date.now() + 601000 || data.pollIntervalMs !== 2000) fail('INVALID_CREATOR_RESPONSE');
422
+ // Expiry is issued and enforced by the platform, not the device clock.
423
+ if (!id(data.authorizationId) || data.status !== 'pending' || !positiveInteger(data.expiresAtMs)
424
+ || data.pollIntervalMs !== 2000) fail('INVALID_CREATOR_RESPONSE');
378
425
  return { public: { authorizationId: data.authorizationId, authorizationUrl: `${platform}/creator/authorize?authorizationId=${data.authorizationId}`,
379
426
  status: 'pending', expiresAtMs: data.expiresAtMs, pollIntervalMs: data.pollIntervalMs },
380
427
  pending: { origin: platform, authorizationId: data.authorizationId, codeVerifier, requestedScopes: [...requestedScopes], projectId: projectId ?? '', expiresAtMs: data.expiresAtMs } };
381
428
  },
382
429
  async exchangeAuthorization(pending, { signal } = {}) {
383
430
  if (!pending || pending.origin !== platform || !id(pending.authorizationId) || !/^[A-Za-z0-9_-]{43}$/.test(pending.codeVerifier ?? '')
384
- || !validScopes(pending.requestedScopes, pending.projectId) || !Number.isSafeInteger(pending.expiresAtMs) || pending.expiresAtMs <= Date.now()) fail('INVALID_AUTHORIZATION_SESSION');
431
+ || !validScopes(pending.requestedScopes, pending.projectId) || !positiveInteger(pending.expiresAtMs)) fail('INVALID_AUTHORIZATION_SESSION');
385
432
  const data = await request('POST', '/token', { body: { authorizationId: pending.authorizationId, codeVerifier: pending.codeVerifier }, signal });
386
433
  if (data.tokenType !== 'Bearer' || !new RegExp(`^ct_${pending.authorizationId}\\.[a-f0-9]{64}$`).test(data.accessToken ?? '')
387
434
  || !validScopes(data.scopes, data.projectId) || data.scopes.some(s => !pending.requestedScopes.includes(s)) || data.projectId !== pending.projectId
388
- || !Number.isSafeInteger(data.expiresAtMs) || data.expiresAtMs <= Date.now() || data.expiresAtMs > Date.now() + 3601000) fail('INVALID_CREATOR_RESPONSE');
435
+ || !positiveInteger(data.expiresAtMs)) fail('INVALID_CREATOR_RESPONSE');
389
436
  return { origin: platform, accessToken: data.accessToken, expiresAtMs: data.expiresAtMs, scopes: [...data.scopes], projectId: data.projectId };
390
437
  },
391
438
  async cancelAuthorization(pending, { signal } = {}) {
392
439
  if (!pending || pending.origin !== platform || !id(pending.authorizationId) || !/^[A-Za-z0-9_-]{43}$/.test(pending.codeVerifier ?? '')) fail('INVALID_AUTHORIZATION_SESSION');
393
440
  return request('POST', `/authorizations/${pending.authorizationId}/cancel`, { body: { codeVerifier: pending.codeVerifier }, signal });
394
441
  },
442
+ async beginModelConnect(pending, { signal } = {}) {
443
+ validateCreatorModelConnectPending(pending, platform);
444
+ const data = await request('POST', `/model-connect/${pending.connectId}/begin`, { signal, body: { ...pending.request,
445
+ codeChallenge: createHash('sha256').update(pending.codeVerifier).digest('base64url'), codeChallengeMethod: 'S256' } });
446
+ return readCreatorModelConnectResult(data, { origin: platform, connectId: pending.connectId, request: pending.request });
447
+ },
448
+ async readModelConnect(pending, { signal, accountId } = {}) {
449
+ validateCreatorModelConnectPending(pending, platform);
450
+ const data = await request('POST', `/model-connect/${pending.connectId}/read`, { signal, body: { codeVerifier: pending.codeVerifier } });
451
+ return readCreatorModelConnectResult(data, { origin: platform, connectId: pending.connectId, request: pending.request, accountId });
452
+ },
453
+ async cancelModelConnect(pending, { signal } = {}) {
454
+ validateCreatorModelConnectPending(pending, platform);
455
+ return request('POST', `/authorizations/${pending.connectId.replaceAll('-', '')}/cancel`,
456
+ { signal, body: { codeVerifier: pending.codeVerifier } });
457
+ },
458
+ async deliverModelConnect(pending, subscriptionToken, { signal, accountId } = {}) {
459
+ validateCreatorModelConnectPending(pending, platform);
460
+ if (!Buffer.isBuffer(subscriptionToken) || subscriptionToken.length === 0 || subscriptionToken.length > 4096)
461
+ fail('INVALID_CREATOR_REQUEST');
462
+ const data = await request('POST', `/model-connect/${pending.connectId}/deliver`, { signal,
463
+ body: { codeVerifier: pending.codeVerifier, subscriptionToken: subscriptionToken.toString('utf8') } });
464
+ return readCreatorModelConnectResult(data, { origin: platform, connectId: pending.connectId, request: pending.request, accountId });
465
+ },
395
466
  async createProject(name, { credential, signal } = {}) {
396
467
  if (typeof name !== 'string' || name.length < 1 || name.length > 80 || /[\u0000-\u001f]/.test(name)) fail('INVALID_CREATOR_REQUEST');
397
468
  try { return await request('POST', '/projects', { body: { name }, credential, signal }); }
@@ -438,16 +509,16 @@ function creatorApi({ origin, allowLocalHttp = false, fetchImpl = globalThis.fet
438
509
  || data.sourceTreeHash !== hash(canonical(data.files)) || !exact(data.archive, ['format', 'sha256', 'bytes'])
439
510
  || data.archive.format !== 'zip-store-v1' || !digest(data.archive.sha256)
440
511
  || !Number.isSafeInteger(data.archive.bytes) || data.archive.bytes < 22 || data.archive.bytes > 73400320
441
- || data.chunkBytes !== 524288 || !Number.isSafeInteger(data.expiresAtMs) || data.expiresAtMs <= Date.now()) fail('INVALID_CREATOR_RESPONSE');
512
+ || data.chunkBytes !== 524288 || !positiveInteger(data.expiresAtMs)) fail('INVALID_CREATOR_RESPONSE');
442
513
  try { validateSourcePackageFiles(data.files); } catch { fail('INVALID_CREATOR_RESPONSE'); }
443
514
  return structuredClone(data);
444
515
  },
445
516
  async getProjectSourceSnapshotChunk(projectId, snapshot, index, options) {
446
517
  if (!snapshot || snapshot.projectId !== projectId || !id(snapshot.snapshotId)
447
518
  || !Number.isSafeInteger(index) || index < 0 || !Number.isSafeInteger(snapshot.archive?.bytes)
448
- || snapshot.archive.bytes < 22 || snapshot.archive.bytes > 73400320) fail('INVALID_SOURCE_SNAPSHOT_REQUEST');
519
+ || snapshot.archive.bytes < 22 || snapshot.archive.bytes > 73400320 || !positiveInteger(snapshot.expiresAtMs)) fail('INVALID_SOURCE_SNAPSHOT_REQUEST');
449
520
  const offset = index * 524288, remaining = snapshot.archive.bytes - offset;
450
- if (remaining <= 0 || snapshot.expiresAtMs <= Date.now()) fail('SOURCE_SNAPSHOT_EXPIRED');
521
+ if (remaining <= 0) fail('INVALID_SOURCE_SNAPSHOT_REQUEST');
451
522
  const data = await request('GET', `${projectPath(projectId)}/source/snapshots/${snapshot.snapshotId}/chunks/${index}`,
452
523
  { ...options, responseLimit: 1048576 });
453
524
  if (!exact(data, ['snapshotId', 'index', 'offset', 'bytes', 'dataBase64', 'archiveSha256', 'archiveBytes', 'complete'])
@@ -17,7 +17,7 @@ import { listLocalCreatorProjects } from './creator-discovery.mjs';
17
17
  import { listCreatorMaterials } from './creator-materials.mjs';
18
18
  import { upgradeCreatorProject, recoverCreatorUpgrade } from './creator-upgrade.mjs';
19
19
  import { creatorReleaseResult } from './creator-platform.mjs';
20
- import { runMeshyCli, meshyMessages } from './meshy-cli.mjs';
20
+ import { runMeshyCli, meshyMessages, meshyFailureDetails } from './meshy-cli.mjs';
21
21
  import { runtimeSourceOptions } from './runtime-source.mjs';
22
22
  import { preparePresentationResources } from './presentation-resources.mjs';
23
23
  import { prepareCreatorSourceGit } from './creator-source-git.mjs';
@@ -25,6 +25,12 @@ import { updatePreparedPresentationProject } from './presentation-project-update
25
25
  import { runtimeHostRejectionCodes, runtimeHostFailureDetails } from './runtime-host-client.mjs';
26
26
 
27
27
  const messages = {
28
+ CREATOR_AGENT_AUTH_UNAVAILABLE: 'The approved personal model sign-in supplier is unavailable. Keep the original profile and request; project upload authorization does not grant model configuration authority. Do not substitute an API key or platform account.',
29
+ CREATOR_AGENT_AUTH_PROTOCOL_INVALID: 'The official sign-in response did not match its supported protocol. Preserve the original operation and inspect its safe status; do not paste raw output, tokens or device codes into chat.',
30
+ CREATOR_AGENT_AUTH_FAILED: 'The original official model sign-in reported failure. Inspect that operation before choosing another explicit action; no model verification or activation is implied.',
31
+ CREATOR_AGENT_AUTH_OUTCOME_UNKNOWN: 'Read the original model sign-in operation by its existing request identity. Do not start a replacement login, resend a code or infer that credentials were saved or writers stopped.',
32
+ CREATOR_AGENT_AUTH_CANCELLED: 'The original model sign-in reports cancellation. Read its own cleanup status; this does not revoke existing credentials or verify, activate or call a model.',
33
+ CREATOR_AGENT_AUTH_EXIT_UNKNOWN: 'Read the original model sign-in request and its owned-writer status. Do not repeat sign-in or launch a replacement while exit or cleanup remains unknown.',
28
34
  CREATOR_PREVIEW_REQUEST_UNCERTAIN: 'Preserve the original private request intent, key and lifetime. Do not POST again or switch keys; latest-job preview-status cannot prove a by-key outcome.',
29
35
  INVALID_CREATOR_PREVIEW_INTENT: 'The private preview request history is invalid or changed. Preserve it; no request was sent.',
30
36
  CREATOR_PREVIEW_HISTORY_FULL: 'The bounded private preview history is full. Preserve this session and its request records; no request was sent.',
@@ -199,6 +205,9 @@ Object.assign(messages, {
199
205
  INSTALL_CONFLICT: 'The existing installation differs or is incomplete. Preserve it and use a separate tools root for explicit recovery; existing AI configuration was not replaced.',
200
206
  INSTALL_BUSY: 'Another initialization owns this exact installation. Wait for that process; do not delete its lock.',
201
207
  INSTALL_NPM_FAILED: 'Dependency installation failed. Check access to the public npm registry and retry the official entry; no partial program was registered.',
208
+ INSTALL_NATIVE_MISSING: 'The exact esbuild dependency or its current-platform optional package is missing. Use the original installer with optional dependencies enabled and the fixed npm cache; no AI registration was changed.',
209
+ INSTALL_NATIVE_VERSION_MISMATCH: 'The installed esbuild version differs from this Kit dependency. Preserve the installation and use the original fixed-package installer; do not substitute latest or another architecture.',
210
+ INSTALL_NATIVE_EXECUTION_FAILED: 'The installed current-platform esbuild could not complete its compiler probe. Preserve the installation and inspect the native dependency result; npm success alone does not prove it works.',
202
211
  INSTALL_CALLER_MISMATCH: 'The initializer and selected release package/version do not match. Preserve the installed tool and verify the explicit platform and matching release metadata. Do not downgrade to an older webpage recommendation, rename the package or rewrite hashes.',
203
212
  INSTALL_PLATFORM_UNSUPPORTED: 'This release metadata has no verified installation for this OS and architecture. Bundled native tools alone do not prove installation or Runtime support. Preserve the project; obtain a release verified for this target, without editing its metadata.',
204
213
  INSTALL_NODE_UNSUPPORTED: 'The initializer requires Node.js 22.16.0 or newer; this is not a requirement to match its build Node patch. Runtime execution has its own declared support. The initializer does not change your Node installation.',
@@ -208,7 +217,7 @@ Object.assign(messages, {
208
217
  SOURCE_UPDATE_OUTSIDE_CONTENT: 'Platform-managed files or untracked files outside content differ. The original project was preserved; update only content through the supported workflow.'
209
218
  });
210
219
 
211
- export function safeFailure(error, { executedCreatorCode = false, cleanup } = {}) {
220
+ export function safeFailure(error, { executedCreatorCode = false, cleanup, includeLocalPaths = false } = {}) {
212
221
  const code = Object.hasOwn(messages, error?.code) || Object.hasOwn(meshyMessages, error?.code) ? error.code : 'CREATOR_OPERATION_FAILED';
213
222
  const provenancePath = code === 'INVALID_RESOURCE' && typeof error?.field === 'string'
214
223
  && /^provenance(?:\.(?:resources|sceneSources)(?:\[\d+\])?(?:\.files\[\d+\])?)?$/.test(error.field)
@@ -224,6 +233,7 @@ export function safeFailure(error, { executedCreatorCode = false, cleanup } = {}
224
233
  ...(code === 'CREATOR_SESSION_SCOPE_REQUIRED' ? { requiredScopes: Array.isArray(error?.requiredScopes) ? error.requiredScopes.filter(scope => ['projects:read', 'source:read', 'contributions:write'].includes(scope)) : [...creatorUploadScopes],
225
234
  missingScopes: (Array.isArray(error?.requiredScopes) ? error.requiredScopes : creatorUploadScopes).filter(scope => Array.isArray(error?.missingScopes) && error.missingScopes.includes(scope)) } : {}) }],
226
235
  executedCreatorCode: executedCreatorCode === false ? false : null, published: false, sensitiveValuesRedacted: true,
236
+ ...meshyFailureDetails(error, { includeLocalPaths }),
227
237
  ...(safeInstallTimings(error?.installationTimings) ? { installationTimings: safeInstallTimings(error.installationTimings) } : {}),
228
238
  ...(safeInstallDiagnostic(error?.installationDiagnostic) ? { installationDiagnostic: safeInstallDiagnostic(error.installationDiagnostic) } : {}),
229
239
  ...(code === 'SOURCE_UPDATE_CONFLICT' && Array.isArray(error?.conflicts) ? { conflictPaths: error.conflicts
@@ -543,5 +553,5 @@ export async function runCreatorCli(args, { initialize = initializeInstalledCrea
543
553
  }
544
554
  emit(result);
545
555
  process.exitCode = result.status === 'passed' ? 0 : result.status === 'needs_capability' ? 2 : result.status === 'cancelled' ? 130 : 1;
546
- } catch (error) { const result = safeFailure(error, localExecution); emit(result); process.exitCode = result.status === 'needs_capability' ? 2 : 1; }
556
+ } catch (error) { const result = safeFailure(error, { ...localExecution, includeLocalPaths: true }); emit(result); process.exitCode = result.status === 'needs_capability' ? 2 : 1; }
547
557
  }
@@ -16,7 +16,7 @@ const scopes = ['projects:read', 'source:read', 'contributions:write'];
16
16
 
17
17
  function access(credential, api, projectId) {
18
18
  if (!projectPattern.test(projectId ?? '') || credential?.origin !== api.origin || credential.projectId !== projectId
19
- || !Number.isSafeInteger(credential.expiresAtMs) || credential.expiresAtMs <= Date.now()) fail('INVALID_CREATOR_CREDENTIAL');
19
+ || !Number.isSafeInteger(credential.expiresAtMs) || credential.expiresAtMs <= 0) fail('INVALID_CREATOR_CREDENTIAL');
20
20
  const missingScopes = scopes.filter(scope => !credential.scopes?.includes(scope));
21
21
  if (missingScopes.length) throw Object.assign(new Error('CREATOR_SESSION_SCOPE_REQUIRED'), { code: 'CREATOR_SESSION_SCOPE_REQUIRED', requiredScopes: scopes, missingScopes });
22
22
  }
@@ -163,12 +163,32 @@ export function safeInstallTimings(value) {
163
163
 
164
164
  export function safeInstallDiagnostic(value) {
165
165
  if (!value || !({ download: ['http-status', 'redirect', 'missing-body', 'content-type', 'size-limit', 'timeout', 'transport'],
166
- npm: ['process-terminated', 'process-failure'] })[value.kind]?.includes(value.reason)) return undefined;
166
+ npm: ['process-terminated', 'process-failure'], native: ['missing', 'version-mismatch', 'probe-failed'] })[value.kind]?.includes(value.reason)) return undefined;
167
167
  if (value.httpStatus !== undefined && (value.kind !== 'download' || value.reason !== 'http-status'
168
168
  || !Number.isInteger(value.httpStatus) || value.httpStatus < 100 || value.httpStatus > 599)) return undefined;
169
169
  return { kind: value.kind, reason: value.reason, ...(value.httpStatus === undefined ? {} : { httpStatus: value.httpStatus }) };
170
170
  }
171
171
 
172
+ export async function installCreatorDependencies({ directory, cache, environment }, execute = exec) {
173
+ const started = performance.now();
174
+ const args = ['install', '--json', '--ignore-scripts', '--no-audit', '--no-fund', '--no-update-notifier',
175
+ '--registry=https://registry.npmjs.org', '--cache', cache, '--userconfig', path.join(directory, 'npm-user.conf'),
176
+ '--globalconfig', path.join(directory, 'npm-global.conf'), './kit.tgz'];
177
+ const run = mode => execute('npm', [...args, mode], { cwd: directory, env: environment,
178
+ timeout: Math.max(1, Math.ceil(180000 - (performance.now() - started))), maxBuffer: 1048576 });
179
+ try { return await run('--offline'); }
180
+ catch (error) {
181
+ // npm may query all optional-platform metadata even with prefer-offline.
182
+ // A complete current-platform cache needs no network. Only npm's explicit
183
+ // cache miss permits the original public GET path in this owned temp root;
184
+ // cancellation, corruption and unknown failures never trigger a replay.
185
+ let code;
186
+ try { code = JSON.parse(error.stdout).error?.code; } catch {}
187
+ if (code !== 'ENOTCACHED' || error.killed || error.signal || performance.now() - started >= 180000) throw error;
188
+ return run('--prefer-offline');
189
+ }
190
+ }
191
+
172
192
  export async function initializeInstalledCreator(options = {}) {
173
193
  const installationTimings = [];
174
194
  const timed = async (phase, action) => {
@@ -244,7 +264,7 @@ async function initialize({ releaseUrl, platform, allowLocalHttp = false, harnes
244
264
  const lockFile = path.join(installations, `${release.artifact.sha256}.lock`);
245
265
  let lock;
246
266
  try { lock = await open(lockFile, 'wx', 0o600); } catch { fail('INSTALL_BUSY'); }
247
- let temporary, installed = false;
267
+ let temporary, installed = false, nativeVerified = false;
248
268
  try {
249
269
  let record;
250
270
  try {
@@ -268,9 +288,8 @@ async function initialize({ releaseUrl, platform, allowLocalHttp = false, harnes
268
288
  await writeFile(path.join(temporary, 'npm-global.conf'), '', { flag: 'wx', mode: 0o600 });
269
289
  const cleanEnvironment = Object.fromEntries(['PATH', 'SystemRoot', 'TMPDIR', 'TEMP', 'TMP'].filter(key => environment[key]).map(key => [key, environment[key]]));
270
290
  try {
271
- await timed('dependencies', () => exec('npm', ['install', '--ignore-scripts', '--no-audit', '--no-fund', '--no-update-notifier', '--prefer-offline', '--registry=https://registry.npmjs.org',
272
- '--cache', npmCache.directory, '--userconfig', path.join(temporary, 'npm-user.conf'), '--globalconfig', path.join(temporary, 'npm-global.conf'), './kit.tgz'],
273
- { cwd: temporary, env: cleanEnvironment, timeout: 180000, maxBuffer: 1048576 }));
291
+ await timed('dependencies', () => installCreatorDependencies({ directory: temporary,
292
+ cache: npmCache.directory, environment: cleanEnvironment }));
274
293
  } catch (cause) {
275
294
  const error = failure('INSTALL_NPM_FAILED');
276
295
  error.installationDiagnostic = { kind: 'npm', reason: cause.killed ? 'process-terminated' : 'process-failure' };
@@ -278,6 +297,8 @@ async function initialize({ releaseUrl, platform, allowLocalHttp = false, harnes
278
297
  }
279
298
  const packageRoot = await readCallerRoot(temporary, release.packageName, current);
280
299
  await timed('verification', () => verifyCaller(packageRoot, platformRoot));
300
+ await timed('verification', () => verifyInstalledCreatorNative(packageRoot));
301
+ nativeVerified = true;
281
302
  const files = await timed('verification', () => inventory(temporary));
282
303
  record = { schemaVersion: 1, sourceSha: release.sourceSha, origin: checked.origin, archiveSha256: release.artifact.sha256,
283
304
  archiveBytes: release.artifact.bytes, toolchain: current, files };
@@ -286,6 +307,7 @@ async function initialize({ releaseUrl, platform, allowLocalHttp = false, harnes
286
307
  }
287
308
  const installedRoot = await readCallerRoot(target, release.packageName, current);
288
309
  await timed('verification', () => verifyCaller(installedRoot, platformRoot));
310
+ if (!nativeVerified) await timed('verification', () => verifyInstalledCreatorNative(installedRoot));
289
311
  const initialized = await timed('registration', () => initializeHarness({ ...selection, workspaceRoot: workspace, platformRoot: installedRoot,
290
312
  platform: creatorOrigin(checked.origin, allowLocalHttp), allowLocalHttp, sessionDirectory: session, replaceFrom,
291
313
  // This is transport for the same package-pinned catalog, not new runtime
@@ -321,3 +343,24 @@ async function verifyCaller(installedRoot, platformRoot) {
321
343
  }
322
344
  } catch { fail('INSTALL_CALLER_MISMATCH'); }
323
345
  }
346
+
347
+ export async function verifyInstalledCreatorNative(installedRoot) {
348
+ // npm optional dependencies can fail without failing npm install. Check the
349
+ // actual installed consumer before registering a supposedly usable tool.
350
+ const metadata = await readCreatorPackageMetadata(installedRoot);
351
+ const probe = `const {createRequire}=require('node:module');
352
+ const r=createRequire(process.argv[1]); let e;
353
+ try { e=r('esbuild'); if(r('esbuild/package.json').version!==process.argv[2])process.exit(2); }
354
+ catch(error) { process.exit(error.code==='MODULE_NOT_FOUND'?3:4); }
355
+ try { if(e.transformSync('let value: number = 1;', {loader:'ts'}).code!=='let value = 1;\\n')process.exit(4); }
356
+ catch { process.exit(4); }`;
357
+ try {
358
+ await exec(process.execPath, ['-e', probe, path.join(installedRoot, 'package.json'), metadata.dependencies.esbuild],
359
+ { cwd: installedRoot, timeout: 10000, maxBuffer: 65536,
360
+ env: Object.fromEntries(['PATH', 'SystemRoot', 'TMPDIR', 'TEMP', 'TMP'].filter(key => process.env[key]).map(key => [key, process.env[key]])) });
361
+ } catch (cause) {
362
+ const error = failure(cause.code === 3 ? 'INSTALL_NATIVE_MISSING' : cause.code === 2 ? 'INSTALL_NATIVE_VERSION_MISMATCH' : 'INSTALL_NATIVE_EXECUTION_FAILED');
363
+ error.installationDiagnostic = { kind: 'native', reason: cause.code === 3 ? 'missing' : cause.code === 2 ? 'version-mismatch' : 'probe-failed' };
364
+ throw error;
365
+ }
366
+ }
@@ -42,6 +42,7 @@ export async function buildCreatorMcp(workspaceRoot, { sessionDirectory, platfor
42
42
  'Omit --runtime-id for dev/test to match pinned manifests to the actual OS, architecture, Node and content tool/contracts. Zero or multiple compatible targets reject explicitly. Do not ask the player for hashes or invent compatibility. An empty authorized catalog means no available material, not permission to read private local sources. For an existing local work use discover_creator_projects, which reads every page by stable creator identity. Reuse a single match; ask the user to choose between multiple matches using literal names and project links, never guess by name. Only complete zero matches with canCreateProject permits offering explicit create_remote_project; use the returned ID in submit, not a user-typed ID. Known association denial or any read error forbids fallback creation. Creation timeout is unknown: do not repeat create, since an empty project cannot be recovered by content discovery. No browser credentials or invented IDs.',
43
43
  'Remote tools require the configured session and current platform permissions. For candidate work, use the installed CLI login --project-id ID --scopes projects:read,source:read,contributions:write; the default owner six-scope authorization does not include candidate write. A candidate never becomes main, a submission, or a release by this tool. Preserve its separate key and read get_creator_contribution_by_key after uncertain replies before editing/submitting B. Read get_creator_preflight for installed tool/capability identity and current invitation eligibility, not a grant. Publish only on explicit user intent. Automatic Testing requests report actual stage/reason/allowedActions; queued, built, published or cancellation intent is not playable or completed cleanup. Independent-review history is read-only. Never force retry reconciling, replace immutable source or treat a transient HTTP failure as workflow failure. Read status serially without overlapping polls. No native test or dev fallback is available.',
44
44
  'An authorized session may lack upload scopes. Read uploadPreflight: source:read is required for blob resume/status, submissions:write for upload/submit, projects:read for live platform preflight. scope-ready is a local scope check only, not project membership or source eligibility. Missing scopes require explicit new authorization; preserve the old session and never silently cancel, widen or edit its permissions. Submit checks scope before scanning content. Honor retryAfterMs on API errors before another read; do not overlap requests or automatically repeat mutations.',
45
+ 'World Agent personal model sign-in is separate from this project upload authorization. Use the existing Studio settings and the user-controlled official interaction; no model-login tool or model-config scope is provided by this MCP session. Never request, display or relay tokens, native auth output or one-time device codes in model chat, MCP arguments or results. An authenticated sign-in is not saved-profile verification, activation, quota or a successful model turn. After an unknown result, preserve and read the original profile/revision/request operation; do not start another login or substitute an API key or platform account. The existing manual Claude SDK route remains explicit and outside model chat. See docs/harness-onboarding.md.',
45
46
  ...(expectedOrigin ? [`Platform fixed by initialization: ${expectedOrigin}. Start with get_creator_authorization. If not started, use begin_creator_authorization and show its authorizationUrl for the user to approve in their normal browser. Only after their confirmation call complete_creator_authorization; pending is not success. Origin, session path and requested scopes cannot be supplied by a tool caller. Authentication does not grant material eligibility, review or publication.`] : [])
46
47
  ].join('\n')
47
48
  });
@@ -19,8 +19,9 @@ export async function beginCreatorOnboarding(options, { fetchImpl } = {}) {
19
19
  const state = await inspectCreatorOnboarding(options);
20
20
  if (state.authorization.phase === 'not-started') return beginCreatorSession({ directory: options.sessionDirectory,
21
21
  origin: state.authorization.origin, allowLocalHttp: options.allowLocalHttp, requestedScopes: creatorAuthorizationScopes, fetchImpl });
22
- if (state.authorization.phase === 'authorized' && state.authorization.expiresAtMs > Date.now()) return state;
23
- if (state.authorization.phase === 'pending' && state.authorization.expiresAtMs > Date.now()) {
22
+ const validExpiry = Number.isSafeInteger(state.authorization.expiresAtMs) && state.authorization.expiresAtMs > 0;
23
+ if (state.authorization.phase === 'authorized' && validExpiry) return state;
24
+ if (state.authorization.phase === 'pending' && validExpiry) {
24
25
  return { ...state, authorizationUrl: `${state.authorization.origin}/creator/authorize?authorizationId=${state.authorization.authorizationId}`, pollIntervalMs: 2000 };
25
26
  }
26
27
  throw failure('CREATOR_SESSION_RENEWAL_REQUIRED');
@@ -44,7 +44,7 @@ export function readProjectDiscovery(data, creatorProjectId, credential) {
44
44
  return structuredClone(data);
45
45
  }
46
46
 
47
- export function readPlatformPreflight(data, projectId, now = Date.now()) {
47
+ export function readPlatformPreflight(data, projectId) {
48
48
  const hashes = ['runtimeHash', 'resourcePolicyHash', 'capabilityRegistryHash', 'capabilitiesLockHash', 'effectivePolicyHash', 'policyHash'];
49
49
  if (!exact(data, ['projectId', 'schemaVersion', 'revision', 'toolchain', ...hashes, 'capabilities', 'policyId', 'validUntilMs', 'observedAtMs', 'releaseEligibility'])
50
50
  || !project(projectId) || data.projectId !== projectId || data.schemaVersion !== '1.0.0' || !positive(data.revision)
@@ -70,7 +70,9 @@ export function readPlatformPreflight(data, projectId, now = Date.now()) {
70
70
  || (durable ? Object.hasOwn(e, 'expiresAtMs') && e.expiresAtMs !== 0
71
71
  : !positive(e.expiresAtMs) || e.expiresAtMs <= data.observedAtMs)) fail('INVALID_CREATOR_RESPONSE');
72
72
  } else if (!exact(e, ['eligible', 'reason']) || e.eligible !== false || e.reason !== 'TESTING_RELEASE_NOT_AUTHORIZED') fail('INVALID_CREATOR_RESPONSE');
73
- if (data.validUntilMs <= now || data.validUntilMs <= data.observedAtMs || e.eligible && !durable && e.expiresAtMs <= now) fail('CREATOR_PREFLIGHT_EXPIRED');
73
+ // Both timestamps share the platform clock. Actual permission/expiry is
74
+ // rechecked by the platform on the operation; device time is not authority.
75
+ if (data.validUntilMs <= data.observedAtMs) fail('CREATOR_PREFLIGHT_EXPIRED');
74
76
  return structuredClone(data);
75
77
  }
76
78
 
@@ -124,7 +124,10 @@ async function assertPlatformFilesUnchanged(original, next, localToolchain) {
124
124
  const metadata = JSON.parse(before);
125
125
  const expected = name === 'chrona.toolchain.json' ? localToolchain : name === 'chrona.project.json'
126
126
  ? { ...metadata, kitVersion: localToolchain.version }
127
- : { ...metadata, devDependencies: { '@chrona/ugc-kit': localToolchain.version } };
127
+ : { ...metadata,
128
+ imports: { [localToolchain.sdk.shared]: `${localToolchain.package}/shared`,
129
+ [localToolchain.sdk.client]: `${localToolchain.package}/client` },
130
+ devDependencies: { [localToolchain.package]: localToolchain.version } };
128
131
  if (canonical(expected) !== canonical(JSON.parse(after))) fail('SOURCE_UPDATE_OUTSIDE_CONTENT');
129
132
  continue;
130
133
  }