@tora-editor/tora 0.2.0 → 0.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 (107) hide show
  1. package/README.md +5 -6
  2. package/bin/tora.mjs +255 -29
  3. package/crates/packer/trusted/native-3d-meta.json +3 -3
  4. package/crates/packer/trusted/native-3d.js +180 -180
  5. package/crates/packer/trusted/native-meta.json +3 -3
  6. package/crates/packer/trusted/native.js +5 -5
  7. package/crates/packer/trusted/release-manifest.json +17 -17
  8. package/crates/packer/trusted/review-runtime-meta.json +3 -3
  9. package/crates/packer/trusted/review-runtime.js +182 -182
  10. package/docs/MIGRATION_0_3.md +39 -0
  11. package/docs/NATIVE_AGENT_TOOLS.md +12 -363
  12. package/docs/TORA_AGENT_SETUP.md +24 -106
  13. package/docs/TORA_CREATION_API.md +63 -365
  14. package/docs/reference/CORE_AUTHORING.md +8 -2
  15. package/docs/reference/PLAYABLE_STARTERS.md +1 -1
  16. package/docs/reference/packs/3d.md +2 -0
  17. package/package.json +6 -6
  18. package/packages/creative-project/project-v21.schema.json +108 -1
  19. package/scripts/lean/editor/entry.js +11 -6
  20. package/scripts/lean/editor/project-launcher.js +116 -0
  21. package/scripts/lean/editor/quick-edit-panel.js +479 -0
  22. package/scripts/lean/editor/review-editor.css +246 -68
  23. package/scripts/lean/editor/review-editor.js +1731 -1099
  24. package/scripts/lean/editor-state.mjs +6 -0
  25. package/scripts/lean/editor.mjs +6 -3
  26. package/scripts/lean/matrix.mjs +5 -0
  27. package/scripts/lean/native/agent-tools.mjs +35 -58
  28. package/scripts/lean/native/api.mjs +148 -134
  29. package/scripts/lean/native/audio-assets.mjs +30 -0
  30. package/scripts/lean/native/browser-pool.mjs +34 -0
  31. package/scripts/lean/native/build-cache.mjs +36 -5
  32. package/scripts/lean/native/contracts.mjs +8 -6
  33. package/scripts/lean/native/creative-qa.mjs +66 -12
  34. package/scripts/lean/native/demos.mjs +11 -20
  35. package/scripts/lean/native/document.mjs +14 -2
  36. package/scripts/lean/native/local-bundle.mjs +4 -2
  37. package/scripts/lean/native/mcp-server.mjs +16 -35
  38. package/scripts/lean/native/modules/harvest-restore.mjs +3 -284
  39. package/scripts/lean/native/modules/sort-puzzle.mjs +51 -0
  40. package/scripts/lean/native/modules/star-salvage.mjs +3 -368
  41. package/scripts/lean/native/project-bundle.mjs +3 -2
  42. package/scripts/lean/native/project-index.mjs +0 -2
  43. package/scripts/lean/native/qa-adapters.mjs +10 -0
  44. package/scripts/lean/native/quick-edit.mjs +328 -0
  45. package/scripts/lean/native/review.mjs +203 -572
  46. package/scripts/lean/native/schema-vocabulary.mjs +10 -0
  47. package/scripts/lean/native/schema.mjs +1 -1
  48. package/scripts/lean/native/scope.mjs +45 -0
  49. package/scripts/lean/native/service.mjs +242 -70
  50. package/scripts/lean/native/starters.mjs +135 -8
  51. package/scripts/lean/native/variant-adapters.mjs +8 -0
  52. package/scripts/lean/native/variants-core.mjs +186 -0
  53. package/scripts/lean/native/variants.mjs +63 -0
  54. package/scripts/lean/native/win-cues.mjs +1 -1
  55. package/skills/tora-playables/SKILL.md +1 -1
  56. package/scripts/lean/editor/review-intake.js +0 -837
  57. package/scripts/lean/model-client.mjs +0 -119
  58. package/scripts/lean/native/author-expansion-proofs.mjs +0 -143
  59. package/scripts/lean/native/author-fps.mjs +0 -545
  60. package/scripts/lean/native/author-games.mjs +0 -160
  61. package/scripts/lean/native/author-harvest.mjs +0 -74
  62. package/scripts/lean/native/author-primitive-proofs.mjs +0 -875
  63. package/scripts/lean/native/author-salvage.mjs +0 -71
  64. package/scripts/lean/native/chat-compose.mjs +0 -287
  65. package/scripts/lean/native/check-harvest-outcome-audio.mjs +0 -190
  66. package/scripts/lean/native/check-salvage.mjs +0 -200
  67. package/scripts/lean/native/compatibility.mjs +0 -34
  68. package/scripts/lean/native/concept.mjs +0 -633
  69. package/scripts/lean/native/draw-stroke.mjs +0 -26
  70. package/scripts/lean/native/erase-mask.mjs +0 -18
  71. package/scripts/lean/native/glb-loader.mjs +0 -468
  72. package/scripts/lean/native/harvest-recipe.mjs +0 -21
  73. package/scripts/lean/native/instance-steering.mjs +0 -24
  74. package/scripts/lean/native/intake-creator-agent.mjs +0 -98
  75. package/scripts/lean/native/intake-creator-tools.mjs +0 -218
  76. package/scripts/lean/native/interaction-gestures.mjs +0 -45
  77. package/scripts/lean/native/match-board.mjs +0 -138
  78. package/scripts/lean/native/modules/index.mjs +0 -54
  79. package/scripts/lean/native/modules/tap-collect.mjs +0 -54
  80. package/scripts/lean/native/path-network.mjs +0 -132
  81. package/scripts/lean/native/physics-2d.mjs +0 -154
  82. package/scripts/lean/native/physics-3d.mjs +0 -259
  83. package/scripts/lean/native/prepare-audio-collections.mjs +0 -112
  84. package/scripts/lean/native/prepare-fps-assets.mjs +0 -330
  85. package/scripts/lean/native/prepare-game-audio.mjs +0 -372
  86. package/scripts/lean/native/prepare-golf-3d-assets.py +0 -177
  87. package/scripts/lean/native/prepare-golf-assets.py +0 -211
  88. package/scripts/lean/native/prepare-harvest-audio.mjs +0 -83
  89. package/scripts/lean/native/prepare-harvest-images.mjs +0 -31
  90. package/scripts/lean/native/prepare-primitive-images.py +0 -25
  91. package/scripts/lean/native/prepare-space-salvage-images.mjs +0 -89
  92. package/scripts/lean/native/prepare-traffic-assets.py +0 -329
  93. package/scripts/lean/native/presentation.mjs +0 -335
  94. package/scripts/lean/native/review-agent-tools.mjs +0 -561
  95. package/scripts/lean/native/review-connection.mjs +0 -303
  96. package/scripts/lean/native/review-fields.mjs +0 -24
  97. package/scripts/lean/native/review-intake.mjs +0 -385
  98. package/scripts/lean/native/review-intents.mjs +0 -217
  99. package/scripts/lean/native/review-provider.mjs +0 -580
  100. package/scripts/lean/native/review-receipts.mjs +0 -76
  101. package/scripts/lean/native/review-resolver.mjs +0 -429
  102. package/scripts/lean/native/review-targets.mjs +0 -35
  103. package/scripts/lean/native/runtime.mjs +0 -1809
  104. package/scripts/lean/native/salvage-recipe.mjs +0 -20
  105. package/scripts/lean/native/stage-3d.mjs +0 -1121
  106. package/scripts/lean/native/verify.mjs +0 -4
  107. package/scripts/lean/scene-document.mjs +0 -48
@@ -94,3 +94,9 @@ export class EditorState{
94
94
  async write(id,state){const path=await this.file(id),temp=path+'.'+randomUUID()+'.tmp';await writeFile(temp,JSON.stringify(state));await rename(temp,path);}
95
95
  async lock(id,fn){id=this.store.root+'\0'+id;const prior=this.queues.get(id)??Promise.resolve();let release;const done=new Promise(r=>release=r);this.queues.set(id,done);await prior;try{return await fn();}finally{release();if(this.queues.get(id)===done)this.queues.delete(id);}}
96
96
  }
97
+
98
+ export async function withProjectFileLock(lockPath,fn,{lockTimeoutMs=15000,staleLockMs=30000}={}){
99
+ const state=Object.create(EditorState.prototype);state.lockTimeoutMs=lockTimeoutMs;state.staleLockMs=staleLockMs;
100
+ const token=await state.acquireFileLock(lockPath);
101
+ try{return await fn();}finally{await state.releaseFileLock(lockPath,token);}
102
+ }
@@ -7,20 +7,22 @@ import {ProjectStore} from './project-store.mjs';
7
7
  import {EditorState} from './editor-state.mjs';
8
8
  import {NativeService} from './native/service.mjs';
9
9
  import {nativeApi} from './native/api.mjs';
10
+ import {closeSharedBrowser,getSharedBrowser} from './native/browser-pool.mjs';
10
11
 
11
12
  const assets = new Map([
12
13
  ['/', ['index.html', 'text/html; charset=utf-8']],
13
14
  ['/entry.js', ['entry.js', 'text/javascript']],
14
15
  ['/review-editor.js', ['review-editor.js', 'text/javascript']],
15
- ['/review-intake.js', ['review-intake.js', 'text/javascript']],
16
+ ['/quick-edit-panel.js', ['quick-edit-panel.js', 'text/javascript']],
17
+ ['/project-launcher.js', ['project-launcher.js', 'text/javascript']],
16
18
  ['/review-editor.css', ['review-editor.css', 'text/css']],
17
19
  ['/brand/manrope.ttf', ['brand/manrope.ttf', 'font/ttf']],
18
20
  ['/brand/mark.svg', ['brand/mark.svg', 'image/svg+xml']],
19
21
  ['/brand/tora-wordmark.svg', ['brand/tora-wordmark.svg', 'image/svg+xml']],
20
22
  ]);
21
23
 
22
- export async function createEditorServer({store = new ProjectStore(), port = 0, connection, agentFactory} = {}) {
23
- const native = nativeApi(new NativeService(store, new EditorState(store)), connection, {agentFactory});
24
+ export async function createEditorServer({store = new ProjectStore(), port = 0} = {}) {
25
+ const native = nativeApi(new NativeService(store, new EditorState(store), {browserProvider: getSharedBrowser}));
24
26
  const server = createServer(async (req, res) => {
25
27
  res.setHeader('Cache-Control', 'no-store');
26
28
  res.setHeader('X-Content-Type-Options', 'nosniff');
@@ -40,6 +42,7 @@ export async function createEditorServer({store = new ProjectStore(), port = 0,
40
42
  res.end(JSON.stringify({error: error.message || 'E_EDITOR_SERVER'}));
41
43
  }
42
44
  });
45
+ server.once('close', () => {void closeSharedBrowser();});
43
46
  await new Promise((done, reject) => {
44
47
  server.once('error', reject);
45
48
  server.listen(port, '127.0.0.1', done);
@@ -0,0 +1,5 @@
1
+ const check=(value,code)=>{if(!value)throw Error(code);};
2
+ export const identityMatrix=()=>[1,0,0,1,0,0];
3
+ export function validateMatrix(matrix){check(Array.isArray(matrix)&&matrix.length===6&&matrix.every(Number.isFinite),'E_SCENE_MATRIX');return matrix;}
4
+ export function multiplyMatrix(left,right){validateMatrix(left);validateMatrix(right);return [left[0]*right[0]+left[2]*right[1],left[1]*right[0]+left[3]*right[1],left[0]*right[2]+left[2]*right[3],left[1]*right[2]+left[3]*right[3],left[0]*right[4]+left[2]*right[5]+left[4],left[1]*right[4]+left[3]*right[5]+left[5]];}
5
+ export function inverseMatrix(matrix){validateMatrix(matrix);const determinant=matrix[0]*matrix[3]-matrix[1]*matrix[2];check(Math.abs(determinant)>1e-12,'E_SCENE_SINGULAR_TRANSFORM');return [matrix[3]/determinant,-matrix[1]/determinant,-matrix[2]/determinant,matrix[0]/determinant,(matrix[2]*matrix[5]-matrix[3]*matrix[4])/determinant,(matrix[1]*matrix[4]-matrix[0]*matrix[5])/determinant];}
@@ -8,12 +8,11 @@ import {NativeService} from './service.mjs';
8
8
  import {runtimeBundle,runtime3dBundle,projectUses3d} from './compiler.mjs';
9
9
  import {exportProjectFile,importProjectPath} from './local-bundle.mjs';
10
10
  import {playableHTML} from './html.mjs';
11
- import {registerSource} from './assets.mjs';
12
11
  import {capabilities,capabilitiesForPacks,compactCapabilities} from './contracts.mjs';
13
- import {composeNativeConcept,CREATIVE_CONCEPT_SCHEMA} from './concept.mjs';
14
12
  import {references,check} from './document.mjs';
15
- const collections=['scenes','components','variables','gameplay','events','eventBindings','assets'];
16
- const mutableCollections=['components','variables','gameplay','events','eventBindings'];
13
+ import {nativeCollections,outsideNativeScope} from './scope.mjs';
14
+ import {NativeReview} from './review.mjs';
15
+ const collections=nativeCollections;
17
16
  const identity=r=>({revisionId:r.revisionId,contentHash:r.contentHash});
18
17
  const round1=n=>Math.round(Number(n)*10)/10;
19
18
  const shortContract=id=>({rectangle:'rect',button:'btn',image:'img',group:'grp',ellipse:'ell',sprite:'spr','walk-sprite':'walk'})[id.replace(/^native\./,'').replace(/\.v1$/,'')]??id.replace(/^native\./,'').replace(/\.v1$/,'');
@@ -21,14 +20,6 @@ function bounded(value,limit){check(Buffer.byteLength(JSON.stringify(value))<=li
21
20
  function pick(record,fields){if(!fields)return record;const result={id:record.id};for(const key of fields){if(Object.hasOwn(record,key))result[key]=record[key];else if(key.startsWith('parameters.')&&Object.hasOwn(record.parameters??{},key.slice(11))){result.parameters??={};result.parameters[key.slice(11)]=record.parameters[key.slice(11)];}}return result;}
22
21
  function descriptors(project,ids,fields){const result={},registry=capabilities().contracts;for(const c of project.components.filter(c=>ids.includes(c.id))){if(!c.contract||!registry[c.contract])continue;const keys=!fields||fields.includes('parameters')?Object.keys(c.parameters):fields.filter(k=>k.startsWith('parameters.')).map(k=>k.slice(11));if(keys.length)result[c.contract]={properties:Object.fromEntries(keys.filter(key=>Object.hasOwn(registry[c.contract].properties,key)).map(key=>[key,registry[c.contract].properties[key]]))};}return result;}
23
22
  function records(project){return collections.flatMap(collection=>project[collection].map(record=>({collection,record})));}
24
- function recordRefs(record){
25
- const refs=[...references(record)];
26
- if(record?.parentId)refs.push(record.parentId);
27
- if(record?.contract==='native.text.v1'&&typeof record.parameters?.text==='string'){
28
- for(const m of record.parameters.text.matchAll(/\{\{([a-z0-9_.-]+)\}\}/g))refs.push(m[1]);
29
- }
30
- return refs;
31
- }
32
23
  function summarizeEvent(event){
33
24
  if(!event)return '?';
34
25
  const target=event.componentId??event.sceneId??event.variableId??event.behaviorId??'';
@@ -102,6 +93,16 @@ export function buildInspectTree(projectId,current,sceneId){
102
93
  scenes,bindings,
103
94
  },16384);
104
95
  }
96
+ function compactMatrixSummary(summary){
97
+ if((summary.entries?.length??0)<=40&&Buffer.byteLength(JSON.stringify(summary))<=200000)return summary;
98
+ const {exports,entries,...pinned}=summary;void exports;void entries;
99
+ return {...pinned,summaryPath:resolve(summary.outputDir,'matrix-summary.json'),exportCount:summary.exports.length,failureCount:summary.failures.length,failures:summary.failures.slice(0,20).map(({blockers,...failure})=>({...failure,blockerCount:blockers?.length??0})),truncated:true};
100
+ }
101
+ async function withInspectBudget(service,input,current,result){
102
+ if(input.includeBudget)result={...result,budget:await service.estimateBudget(current.project.projectId,{target:input.target??'standalone-browser-draft',variantId:input.variantId,revisionId:current.revisionId})};
103
+ if(input.includeReview)result={...result,review:await new NativeReview(service).summaries(current.project.projectId)};
104
+ return result;
105
+ }
105
106
  export class NativeAgentTools{
106
107
  constructor(service=new NativeService(new ProjectStore(resolve('.tora/native-projects')),undefined)){this.service=service;this.previewCache=new Map();if(!service.history)service.history=new EditorState(service.store);}
107
108
  async run(input){check(input&&typeof input==='object'&&!Array.isArray(input),'E_AGENT_ARGUMENT');const {command,id}=input;
@@ -111,9 +112,7 @@ export class NativeAgentTools{
111
112
  if(input.names!==undefined)check(Array.isArray(input.names)&&input.names.length>0&&input.names.length<=16,'E_AGENT_CONTRACT_SCOPE');
112
113
  else check(Boolean(input.packs),'E_AGENT_CONTRACT_SCOPE');
113
114
  if(input.format==='compact'){
114
- const rawNames=input.names??[],wantsConcept=rawNames.includes('creative-concept'),otherNames=rawNames.filter(n=>n!=='creative-concept');
115
- const result=input.packs||otherNames.length?compactCapabilities({packs:input.packs,names:otherNames.length?otherNames:undefined}):{format:'tora-creation-capabilities-compact-1'};
116
- if(wantsConcept)result['creative-concept']=CREATIVE_CONCEPT_SCHEMA;
115
+ const result=input.packs||input.names?.length?compactCapabilities({packs:input.packs,names:input.names}):{format:'tora-creation-capabilities-compact-1'};
117
116
  return bounded(result,input.packs?65536:24576);
118
117
  }
119
118
  const cap=capabilities();
@@ -121,7 +120,6 @@ export class NativeAgentTools{
121
120
  for(const name of input.names??[]){
122
121
  if(cap.contracts[name]){if(input.packs){result.contracts??={};result.contracts[name]=cap.contracts[name];}else result[name]=cap.contracts[name];}
123
122
  else if(cap.behaviors[name]){if(input.packs){result.behaviors??={};result.behaviors[name]=cap.behaviors[name];}else result[name]=cap.behaviors[name];}
124
- else if(name==='creative-concept')result['creative-concept']=CREATIVE_CONCEPT_SCHEMA;
125
123
  else if(name==='operations')result.operations=cap.operations;
126
124
  else if(name==='actions')result.actions=cap.actions;
127
125
  else if(name==='events')result.events=cap.events;
@@ -130,37 +128,21 @@ export class NativeAgentTools{
130
128
  }
131
129
  return bounded(result,input.packs?65536:24576);
132
130
  }
133
- if(command==='compose'){
134
- const composition=composeNativeConcept(input.concept);
135
- const summary={status:'COMPOSED',projectId:id,conceptHash:composition.conceptHash,conceptAccepted:false,accepted:false,creativeStatus:composition.creativeStatus,unmetRequirements:composition.unmetRequirements,requirements:composition.requirements,...(composition.recipe?{recipe:composition.recipe}:{})};
136
- // Check response capacity before creating a project or committing a revision.
137
- bounded({...summary,expected:{revisionId:'rev-'+'0'.repeat(36),contentHash:'sha256:'+'0'.repeat(64)}},24576);
138
- const created=await this.service.create({id,name:input.name??input.concept?.product?.name});
139
- const registered=new Map();for(const asset of composition.assets)registered.set(asset.id,await registerSource(resolve(this.service.store.root,id),asset));
140
- const operations=composition.operations.map(operation=>{if(operation.kind!=='registerAsset'||!registered.has(operation.asset.id))return operation;const metadata=registered.get(operation.asset.id);return {...operation,asset:{...operation.asset,hash:metadata.hash,mime:metadata.mime,bytes:metadata.bytes}};});
141
- const envelope={format:'tora-transaction-1',expected:identity(created),operations};
142
- const preview=await this.service.preview(id,envelope);
143
- const record=composition.recipe?(state,revision)=>{
144
- state.authoring={recipe:composition.recipe,conceptHash:composition.conceptHash,createdRevisionId:revision.revisionId};
145
- }:undefined;
146
- const result=await this.service.transact(id,{...envelope,previewDigest:preview.previewDigest},{record});
147
- return {...summary,expected:identity(result)};
148
- }
149
131
  if(command==='create'){const r=await this.service.create({id,name:input.name,...(input.androidUrl?{androidUrl:input.androidUrl}:{})});return bounded({status:'CREATED',projectId:id,expected:identity(r)},4096);}
150
132
  if(command==='import'){check(typeof input.file==='string','E_AGENT_ARGUMENT');return bounded(await importProjectPath(this.service,input.file,{copy:input.copy===true}),4096);}
151
- if(command==='export'&&input.format==='project'){check(typeof input.output==='string'&&input.output.length>0,'E_AGENT_OUTPUT');const text=await exportProjectFile(this.service,id),output=resolve(input.output);await mkdir(dirname(output),{recursive:true});await writeFile(output,text);return {status:'EXPORTED',projectId:id,output,format:'tora-project-bundle',version:1};}
133
+ if(command==='export'&&input.format==='project'){check(typeof input.output==='string'&&input.output.length>0,'E_AGENT_OUTPUT');const text=await exportProjectFile(this.service,id),output=resolve(input.output);await mkdir(dirname(output),{recursive:true});await writeFile(output,text);return {status:'EXPORTED',projectId:id,output,format:'tora-project-bundle',version:JSON.parse(text).version};}
152
134
  const current=await this.service.read(id,input.revisionId);
153
135
  if(command==='inspect'){
154
- if(input.full)return {projectId:id,expected:identity(current),accepted:current.accepted,project:current.project};
155
- if(input.tree)return buildInspectTree(id,current,input.sceneId);
136
+ if(input.full)return withInspectBudget(this.service,input,current,{projectId:id,expected:identity(current),accepted:current.accepted,project:current.project});
137
+ if(input.tree)return withInspectBudget(this.service,input,current,buildInspectTree(id,current,input.sceneId));
156
138
  const all=records(current.project);
157
139
  if(input.ids){check(Array.isArray(input.ids)&&input.ids.length>0&&input.ids.length<=64&&new Set(input.ids).size===input.ids.length,'E_AGENT_SCOPE');check(input.ids.every(id=>all.some(x=>x.record.id===id)),'E_AGENT_UNKNOWN_RECORD');if(input.fields)check(Array.isArray(input.fields)&&input.fields.every(k=>typeof k==='string'),'E_AGENT_FIELDS');const selected=new Set(input.ids),needed=new Set(input.ids);for(const id of input.ids){let component=current.project.components.find(c=>c.id===id);while(component){needed.add(component.sceneId);if(component.parentId)needed.add(component.parentId);component=current.project.components.find(c=>c.id===component.parentId);}}
158
140
  for(const {record}of all)if(selected.has(record.id))for(const ref of references(record))needed.add(ref);
159
141
  const related=all.filter(({record})=>needed.has(record.id)||references(record).some(ref=>selected.has(ref)));
160
- return bounded({projectId:id,expected:identity(current),records:related.map(({collection,record})=>({collection,...pick(record,selected.has(record.id)?input.fields:undefined)})),contracts:descriptors(current.project,input.ids,input.fields)},24576);
142
+ return bounded(await withInspectBudget(this.service,input,current,{projectId:id,expected:identity(current),records:related.map(({collection,record})=>({collection,...pick(record,selected.has(record.id)?input.fields:undefined)})),contracts:descriptors(current.project,input.ids,input.fields)}),24576);
161
143
  }
162
- if(input.search!==undefined){check(typeof input.search==='string'&&input.search.length<=128,'E_AGENT_ARGUMENT');const query=input.search.toLowerCase();return bounded({projectId:id,expected:identity(current),matches:all.filter(({record})=>(record.id+' '+(record.label??'')).toLowerCase().includes(query)).map(({collection,record})=>({collection,id:record.id,label:record.label}))},8192);}
163
- return bounded({projectId:id,expected:identity(current),goal:current.project.creativeBrief.goal,scenes:current.project.scenes,counts:Object.fromEntries(collections.map(k=>[k,current.project[k].length])),targets:capabilities().targets},8192);
144
+ if(input.search!==undefined){check(typeof input.search==='string'&&input.search.length<=128,'E_AGENT_ARGUMENT');const query=input.search.toLowerCase();return bounded(await withInspectBudget(this.service,input,current,{projectId:id,expected:identity(current),matches:all.filter(({record})=>(record.id+' '+(record.label??'')).toLowerCase().includes(query)).map(({collection,record})=>({collection,id:record.id,label:record.label}))}),8192);}
145
+ return bounded(await withInspectBudget(this.service,input,current,{projectId:id,expected:identity(current),goal:current.project.creativeBrief.goal,scenes:current.project.scenes,counts:Object.fromEntries(collections.map(k=>[k,current.project[k].length])),targets:capabilities().targets}),8192);
164
146
  }
165
147
  if(command==='edit'){
166
148
  check(input.expected&&Array.isArray(input.scope)&&input.scope.every(s=>typeof s==='string'),'E_AGENT_ARGUMENT');
@@ -186,23 +168,7 @@ export class NativeAgentTools{
186
168
  this.previewCache.set(previewDigest,{id,expected:input.expected,operations,previewDigest,changed,warnings,previewProject});
187
169
  while(this.previewCache.size>16)this.previewCache.delete(this.previewCache.keys().next().value);
188
170
  }
189
- const scope=new Set(input.scope);
190
- let outside;
191
- if(input.scopeCreates){
192
- const existingAll=new Set(collections.flatMap(col=>current.project[col].map(r=>r.id)));
193
- const existingMutable=new Set(mutableCollections.flatMap(col=>current.project[col].map(r=>r.id)));
194
- const previewById=new Map(collections.flatMap(col=>previewProject[col].map(r=>[r.id,r])));
195
- outside=changed.filter(cid=>{
196
- if(scope.has(cid))return false;
197
- if(cid==='$project.base'||existingAll.has(cid))return true;
198
- const rec=previewById.get(cid);
199
- if(!rec)return true;
200
- const refs=recordRefs(rec);
201
- return refs.some(ref=>existingMutable.has(ref)&&!scope.has(ref));
202
- });
203
- }else{
204
- outside=changed.filter(cid=>!scope.has(cid));
205
- }
171
+ const outside=outsideNativeScope(current.project,previewProject,changed,input.scope,input.scopeCreates===true);
206
172
  // Explicit scope includes all intended writes (or reference-safe creates when scopeCreates:true).
207
173
  if(input.previewOnly||outside.length){return bounded({status:'PREVIEW',expected:input.expected,previewDigest,changedIds:changed,outsideScope:outside,warnings},24576);}
208
174
  if(input.previewDigest)check(input.previewDigest===previewDigest,'E_NATIVE_PREVIEW_STALE');
@@ -211,16 +177,27 @@ export class NativeAgentTools{
211
177
  this.previewCache.delete(previewDigest);
212
178
  return {...summary,expected:identity(result)};
213
179
  }
180
+ if(command==='variants'){
181
+ check(['list','diff','upsert','delete','preset'].includes(input.action),'E_AGENT_ARGUMENT');
182
+ if(input.action==='list')return this.service.listVariants(id);
183
+ if(input.action==='diff'){check(typeof input.variantId==='string'&&input.variantId.length>0,'E_AGENT_ARGUMENT');return this.service.diffVariant(id,input.variantId,{revisionId:input.revisionId});}
184
+ if(input.action==='upsert'){check(input.variant&&typeof input.variant==='object','E_AGENT_ARGUMENT');return this.service.upsertVariant(id,input.variant,{expectedVariantRevision:input.expectedVariantRevision});}
185
+ if(input.action==='delete'){check(typeof input.variantId==='string'&&input.variantId.length>0,'E_AGENT_ARGUMENT');return this.service.deleteVariant(id,input.variantId,{expectedVariantRevision:input.expectedVariantRevision});}
186
+ check(typeof input.variantId==='string'&&input.variantId.length>0&&typeof input.preset==='string'&&input.preset.length>0,'E_AGENT_ARGUMENT');
187
+ const {command:cmd,variantId,...preset}=input;void cmd;
188
+ return this.service.createPresetVariant(id,{...preset,id:variantId});
189
+ }
214
190
  if(command==='history'){check(input.expected,'E_AGENT_EXPECTED');const r=await this.service.navigate(id,{expected:input.expected,action:input.action});return {status:'SAVED',expected:identity(r)};}
215
191
  if(command==='export'||command==='render'||command==='qa'){
216
- if(command==='qa'){const output=input.output!==undefined?resolve(input.output):undefined;return bounded(await this.service.runQa(id,{revisionId:current.revisionId,target:input.target??'standalone-browser-draft',...(output?{outputDir:output}:{}),...(input.motionFilmstrip!==undefined?{motionFilmstrip:input.motionFilmstrip}:{}),...(input.recordVideo!==undefined?{recordVideo:input.recordVideo}:{}),...(input.fitTargetBudget!==undefined?{fitTargetBudget:Boolean(input.fitTargetBudget)}:{})}),65536);}
192
+ if(command==='qa'){const output=input.output!==undefined?resolve(input.output):undefined;return bounded(await this.service.runQa(id,{revisionId:current.revisionId,target:input.target??'standalone-browser-draft',...(output?{outputDir:output}:{}),...(input.motionFilmstrip!==undefined?{motionFilmstrip:input.motionFilmstrip}:{}),...(input.recordVideo!==undefined?{recordVideo:input.recordVideo}:{}),...(input.fitTargetBudget!==undefined?{fitTargetBudget:Boolean(input.fitTargetBudget)}:{}),...(input.variantId?{variantId:input.variantId}:{}),...(input.confirmReviewed?{confirmReviewed:input.confirmReviewed}:{})}),65536);}
217
193
  if(command==='export'&&input.targets!==undefined){
218
194
  check(input.format===undefined&&input.output===undefined&&input.target===undefined,'E_AGENT_ARGUMENT');
219
195
  check(typeof input.outputDir==='string'&&input.outputDir.length>0,'E_AGENT_OUTPUT');
220
- return bounded(await this.service.exportBatch(id,{revisionId:current.revisionId,targets:input.targets,outputDir:input.outputDir,...(input.fitTargetBudget!==undefined?{fitTargetBudget:Boolean(input.fitTargetBudget)}:{})}),16384);
196
+ if(input.variants!==undefined)return bounded(compactMatrixSummary(await this.service.exportVariantMatrix(id,{revisionId:current.revisionId,targets:input.targets,variants:input.variants,outputDir:input.outputDir,...(input.fitTargetBudget!==undefined?{fitTargetBudget:Boolean(input.fitTargetBudget)}:{}),...(input.confirmReviewed?{confirmReviewed:input.confirmReviewed}:{})})),262144);
197
+ return bounded(await this.service.exportBatch(id,{revisionId:current.revisionId,targets:input.targets,outputDir:input.outputDir,...(input.fitTargetBudget!==undefined?{fitTargetBudget:Boolean(input.fitTargetBudget)}:{}),...(input.variantId?{variantId:input.variantId}:{}),...(input.confirmReviewed?{confirmReviewed:input.confirmReviewed}:{})}),16384);
221
198
  }
222
199
  check(typeof input.output==='string'&&input.output.length>0,'E_AGENT_OUTPUT');const output=resolve(input.output);let html,archiveBytes,artifactHash,sceneId,manifest;
223
- if(command==='render'){sceneId=input.sceneId??current.project.base.startScene;check(current.project.scenes.some(scene=>scene.id===sceneId),'E_AGENT_UNKNOWN_SCENE');const render=await this.service.render(id,current.revisionId);html=playableHTML({...current.project,assets:render.assets},projectUses3d(current.project)?await runtime3dBundle():await runtimeBundle(),{edit:true,sceneId});const {hash}=await import('./compiler.mjs');artifactHash=hash(html);}else{const artifact=await this.service.export(id,{revisionId:current.revisionId,target:input.target??'standalone-browser-draft',...(input.fitTargetBudget!==undefined?{fitTargetBudget:Boolean(input.fitTargetBudget)}:{})});html=artifact.html;archiveBytes=artifact.archiveBytes;artifactHash=artifact.manifest.artifactHash;manifest=artifact.manifest;if(artifact.archiveBytes){check(output.toLowerCase().endsWith('.zip'),'E_AGENT_OUTPUT');if((input.target??'') === 'mintegral-appgrowth-zip')check(basename(output)===`${id}.zip`,'E_AGENT_OUTPUT');}}
200
+ if(command==='render'){sceneId=input.sceneId??current.project.base.startScene;check(current.project.scenes.some(scene=>scene.id===sceneId),'E_AGENT_UNKNOWN_SCENE');const render=await this.service.render(id,current.revisionId);html=playableHTML({...current.project,assets:render.assets},projectUses3d(current.project)?await runtime3dBundle():await runtimeBundle(),{edit:true,sceneId});const {hash}=await import('./compiler.mjs');artifactHash=hash(html);}else{const artifact=await this.service.export(id,{revisionId:current.revisionId,target:input.target??'standalone-browser-draft',...(input.fitTargetBudget!==undefined?{fitTargetBudget:Boolean(input.fitTargetBudget)}:{}),...(input.variantId?{variantId:input.variantId}:{}),...(input.confirmReviewed?{confirmReviewed:input.confirmReviewed}:{})});html=artifact.html;archiveBytes=artifact.archiveBytes;artifactHash=artifact.manifest.artifactHash;manifest=artifact.manifest;if(artifact.archiveBytes){check(output.toLowerCase().endsWith('.zip'),'E_AGENT_OUTPUT');if((input.target??'') === 'mintegral-appgrowth-zip')check(basename(output)===`${id}.zip`,'E_AGENT_OUTPUT');}else if(input.target&&input.target!=='standalone-browser-draft')check(basename(output)==='index.html','E_AGENT_OUTPUT');}
224
201
  await mkdir(dirname(output),{recursive:true});await writeFile(output,archiveBytes??html);return bounded({status:command==='render'?'RENDER_READY':'EXPORTED',projectId:id,expected:identity(current),output,artifactHash,target:command==='render'?'editor-preview':input.target??'standalone-browser-draft',...(manifest?{bytes:manifest.bytes,packaging:manifest.packaging,...(manifest.budgetOptimization?{fitTargetBudget:true}:{})}:{}),...(sceneId?{sceneId,edit:true}:{})},4096);
225
202
  }
226
203
  throw Error('E_AGENT_COMMAND');
@@ -1,16 +1,11 @@
1
- import process from 'node:process';
2
1
  import {Buffer} from 'node:buffer';
2
+ import {readFile,stat} from 'node:fs/promises';
3
3
  import {parseAuthoringJson} from '../../../packages/creative-project/src/strict-json.mjs';
4
4
  import {capabilities,capabilitiesForPacks,capabilitySummary,compactCapabilities,limits} from './contracts.mjs';
5
5
  import {buildInspectTree,NativeAgentTools} from './agent-tools.mjs';
6
6
  import {check,exact} from './document.mjs';
7
7
  import {NativeReview} from './review.mjs';
8
- import {ReviewConnection} from './review-connection.mjs';
9
- import {configuredReviewAgent,configuredReviewInterpreter,reviewRoutingFlags} from './review-resolver.mjs';
10
- import {reviewProviderConfig} from './review-provider.mjs';
11
- import {ReviewIntake} from './review-intake.mjs';
12
8
  import {reviewRuntimeBundle} from './compiler.mjs';
13
- import {composeFromFreePack,freePackPreview,listFreePacks} from './chat-compose.mjs';
14
9
  import {listDemosWithStatus,materializeDemo} from './demos.mjs';
15
10
  import {AssetCatalog} from './asset-catalog.mjs';
16
11
  import {RemoteCc0Fetcher} from './remote-cc0-fetcher.mjs';
@@ -19,81 +14,54 @@ import {fetchCc0Properties} from './cc0-inputs.mjs';
19
14
  import {prepAssets} from './asset-prep.mjs';
20
15
  import {PACKAGE_ROOT} from '../runtime-paths.mjs';
21
16
  import {projectWinCueTrack,replaceProjectWinCue,winCuePreview} from './win-cues.mjs';
17
+ import {composeStarter,listStarters} from './starters.mjs';
18
+ import {importProjectFile} from './local-bundle.mjs';
19
+ import {BUNDLE_LIMIT} from './project-bundle.mjs';
20
+ import {buildQuickEditOperations,summarizeQuickEdit} from './quick-edit.mjs';
21
+ import {lowerAssets} from './assets.mjs';
22
+ import {assertStorePath} from './store-path.mjs';
23
+ import {randomUUID} from 'node:crypto';
24
+ import {relative,resolve,sep} from 'node:path';
22
25
 
23
- const connectionErrors={
24
- E_REVIEW_KEY_FORMAT:400,E_REVIEW_KEY_SAVE:500,E_MODEL_AUTH:401,E_MODEL_FORBIDDEN:403,
25
- E_MODEL_QUOTA:402,E_MODEL_UNAVAILABLE:422,E_MODEL_UNSUPPORTED_CAPABILITY:422,
26
- E_MODEL_RATE_LIMIT:429,E_MODEL_TIMEOUT:504,E_MODEL_TRANSPORT:502,
27
- E_MODEL_UPSTREAM:502,E_MODEL_REQUEST:502,
28
- };
29
- export function nativeApi(service,connection=new ReviewConnection(service.store.root),{agentFactory,catalog,remoteFetcher}={}){
30
- const intakes=new ReviewIntake(service,{connection,agentFactory});
26
+ export function nativeApi(service,{catalog,remoteFetcher}={}){
27
+ const review=new NativeReview(service);
31
28
  const assetCatalog=catalog??new AssetCatalog({root:PACKAGE_ROOT});
32
29
  const cc0Fetcher=remoteFetcher??new RemoteCc0Fetcher({workspaceRoot:service.store.workspaceRoot,catalog:assetCatalog});
33
- const providerForConnection=async()=>{
34
- if(process.env.TORA_REVIEW_PROVIDER){
35
- const config=reviewProviderConfig();
36
- return {
37
- config,
38
- info:config?{
39
- provider:config.provider,
40
- providerLabel:config.provider,
41
- model:config.model,
42
- modelLabel:config.model,
43
- vision:Boolean(config.vision),
44
- verified:config.provider!=='orca'&&config.provider!=='openai-compatible',
45
- }:undefined,
46
- };
47
- }
48
- const active=await connection.read();
49
- if(!active)return {config:undefined,info:undefined};
50
- const config=reviewProviderConfig({
51
- provider:active.provider,
52
- model:active.model,
53
- endpoint:active.endpoint,
54
- apiKey:active.apiKey,
55
- vision:active.vision,
56
- });
57
- return {
58
- config,
59
- info:{
60
- provider:active.provider,
61
- providerLabel:active.providerLabel,
62
- model:active.model,
63
- modelLabel:active.modelLabel,
64
- capabilities:active.capabilities,
65
- audioSummary:active.audioSummary,
66
- videoSummary:active.videoSummary,
67
- verified:Boolean(active.verified),
68
- legacy:Boolean(active.legacy),
69
- },
70
- };
30
+ const matrixJobs=new Map();
31
+ const availableTemplates=async()=>{
32
+ const starterInfo=listStarters();
33
+ return {starters:starterInfo.starters,defaults:starterInfo.defaults,templates:starterInfo.starters.map(item=>({
34
+ id:item.id,kind:'starter',name:item.name,genre:item.genre,description:item.tagline,
35
+ mechanic:item.mechanic,previews:[],defaults:starterInfo.defaults,
36
+ }))};
71
37
  };
72
- const reviewForConnection=async()=>{
73
- const {config:provider,info:connectionInfo}=await providerForConnection();
74
- const routing=reviewRoutingFlags();
75
- return new NativeReview(service,{
76
- agent:configuredReviewAgent(provider,connection.fetch),
77
- interpreter:routing.interpretation?configuredReviewInterpreter(provider,connection.fetch):undefined,
78
- deterministic:routing.deterministic,
79
- connectionInfo,
80
- });
38
+ const uniqueSlug=async(raw,fallback)=>{
39
+ const base=String(raw??'').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^[^a-z]+/,'').replace(/-+$/,'').slice(0,38);
40
+ const slug=base.length>=2&&base!=='compose'?base:fallback;
41
+ const existing=new Set((await service.store.list()).map(p=>p.id));
42
+ if(!existing.has(slug))return slug;
43
+ for(let n=2;n<999;n++){
44
+ const suffix='-'+n;
45
+ const candidate=slug.slice(0,48-suffix.length)+suffix;
46
+ if(!existing.has(candidate))return candidate;
47
+ }
48
+ throw Error('E_PROJECT_EXISTS');
81
49
  };
82
50
  return async(req,res,url,port)=>{
83
- const match=/^\/api\/projects\/([a-z][a-z0-9-]{1,47})(?:\/(transactions\/preview|transactions|history|accept|export|render|review|win-cue|stage-cc0|assets(?:\/[a-z][a-z0-9_.-]{0,95})?))?$/.exec(url.pathname);
84
- const intake=/^\/api\/review-intakes(?:\/([a-f0-9-]{36})(?:\/(submit|assets|references|cancel|retry)(?:\/([a-z0-9_.-]+))?)?)?$/.exec(url.pathname);
85
- const previewMatch=/^\/api\/catalog\/preview\/([a-z0-9-]+)$/.exec(url.pathname);
51
+ if(['/api/projects/from-chat','/api/projects/compose'].includes(url.pathname))return false;
52
+ const match=/^\/api\/projects\/([a-z][a-z0-9-]{1,47})(?:\/(transactions\/preview|transactions|history|accept|export|render|review|win-cue|stage-cc0|budget|variants|export-matrix|quick-edit|qa-asset|qa|assets(?:\/[a-z][a-z0-9_.-]{0,95}(?:\/raw)?)?))?$/.exec(url.pathname);
53
+ const matrixJob=/^\/api\/projects\/([a-z][a-z0-9-]{1,47})\/export-matrix\/([a-f0-9-]{36})$/.exec(url.pathname);
86
54
  const winCueMatch=/^\/api\/catalog\/win-cues\/([a-z0-9-]+)$/.exec(url.pathname);
87
- const connectionRoute=url.pathname==='/api/review/connection';
88
- const catalogRoute=url.pathname==='/api/catalog/packs';
55
+ const startersRoute=url.pathname==='/api/starters';
56
+ const startersComposeRoute=url.pathname==='/api/starters/compose';
57
+ const importProjectRoute=url.pathname==='/api/projects/import';
89
58
  const assetsCatalogRoute=url.pathname==='/api/assets/catalog';
90
59
  const assetsFetchRoute=url.pathname==='/api/assets/fetch-cc0';
91
60
  const assetsPrepRoute=url.pathname==='/api/assets/prep';
92
- const fromChatRoute=url.pathname==='/api/projects/from-chat';
93
61
  const demosRoute=url.pathname==='/api/demos';
94
62
  const demosOpenRoute=url.pathname==='/api/demos/open';
95
- const top=connectionRoute||catalogRoute||assetsCatalogRoute||assetsFetchRoute||assetsPrepRoute||fromChatRoute||demosRoute||demosOpenRoute||['/api/open','/api/creation/capabilities','/api/projects'].includes(url.pathname);
96
- if(!match&&!intake&&!previewMatch&&!winCueMatch&&!top&&url.pathname!=='/review-runtime.js')return false;
63
+ const top=startersRoute||startersComposeRoute||importProjectRoute||assetsCatalogRoute||assetsFetchRoute||assetsPrepRoute||demosRoute||demosOpenRoute||['/api/open','/api/creation/capabilities','/api/projects'].includes(url.pathname);
64
+ if(!match&&!matrixJob&&!winCueMatch&&!top&&url.pathname!=='/review-runtime.js')return false;
97
65
  const json=(status,value)=>{res.writeHead(status,{'Content-Type':'application/json'});res.end(JSON.stringify(value));};
98
66
  try{check(req.headers.host==='127.0.0.1:'+port,'E_NATIVE_ORIGIN');
99
67
  if(url.pathname==='/review-runtime.js'){
@@ -106,9 +74,35 @@ export function nativeApi(service,connection=new ReviewConnection(service.store.
106
74
  res.writeHead(200,{'Content-Type':asset.mime,'X-Content-Type-Options':'nosniff'});res.end(asset.bytes);
107
75
  return true;
108
76
  }
109
- if(catalogRoute){
77
+ if(startersRoute){
110
78
  check(req.method==='GET','E_NATIVE_METHOD');
111
- json(200,await listFreePacks());return true;
79
+ json(200,await availableTemplates());return true;
80
+ }
81
+ if(match?.[2]==='qa-asset'&&req.method==='GET'){
82
+ const rel=url.searchParams.get('file');
83
+ check(typeof rel==='string'&&rel.length>0&&rel.length<=260&&!rel.includes('\0')&&!rel.startsWith('/')&&!rel.includes('..')&&!rel.includes('\\')&&!rel.split('/').some(seg=>!seg||seg.startsWith('.'))&&/\.(?:png|jpg|jpeg|webp)$/i.test(rel),'E_NATIVE_ARGUMENT');
84
+ const qaRoot=resolve(service.store.root,match[1],'qa');
85
+ const target=resolve(qaRoot,rel);
86
+ check(target.startsWith(qaRoot+sep),'E_NATIVE_NOT_FOUND');
87
+ await assertStorePath(target);
88
+ const info=await stat(target);
89
+ check(info.isFile(),'E_NATIVE_NOT_FOUND');
90
+ const bytes=await readFile(target);
91
+ const ext=rel.toLowerCase().split('.').pop();
92
+ const mime=ext==='png'?'image/png':ext==='webp'?'image/webp':'image/jpeg';
93
+ res.writeHead(200,{'Content-Type':mime,'X-Content-Type-Options':'nosniff'});res.end(bytes);
94
+ return true;
95
+ }
96
+ const rawAssetMatch=match?.[2]&&req.method==='GET'?/^assets\/([a-z][a-z0-9_.-]{0,95})\/raw$/.exec(match[2]):null;
97
+ if(rawAssetMatch){
98
+ const assetId=rawAssetMatch[1];
99
+ const current=await service.read(match[1]);
100
+ const asset=current.project.assets.find(item=>item.id===assetId);
101
+ check(asset,'E_NATIVE_NOT_FOUND');
102
+ const [lowered]=await lowerAssets(resolve(service.store.root,match[1]),[asset]);
103
+ res.writeHead(200,{'Content-Type':asset.mime,'X-Content-Type-Options':'nosniff'});
104
+ res.end(Buffer.from(lowered.data,'base64'));
105
+ return true;
112
106
  }
113
107
  if(assetsCatalogRoute){
114
108
  check(req.method==='GET','E_NATIVE_METHOD');
@@ -129,56 +123,33 @@ export function nativeApi(service,connection=new ReviewConnection(service.store.
129
123
  check(req.method==='GET','E_NATIVE_METHOD');
130
124
  json(200,{demos:await listDemosWithStatus(service)});return true;
131
125
  }
132
- if(previewMatch){
133
- check(req.method==='GET','E_NATIVE_METHOD');
134
- const file=await freePackPreview(previewMatch[1]);
135
- res.writeHead(200,{'Content-Type':file.mime,'X-Content-Type-Options':'nosniff','Cache-Control':'public, max-age=3600'});
136
- res.end(file.bytes);return true;
137
- }
138
- if(connectionRoute&&req.method==='GET'){
139
- json(200,await connection.status());return true;
140
- }
141
- if(intake&&req.method==='GET'){
142
- const [,id,route,assetId]=intake;
143
- if((route==='assets'||route==='references')&&assetId){
144
- const asset=route==='references'?await intakes.referenceAsset(id,assetId):await intakes.asset(id,assetId);
145
- res.writeHead(200,{'Content-Type':asset.mime,'X-Content-Type-Options':'nosniff'});res.end(asset.bytes);
146
- }else{
147
- check(id&&!route,'E_NATIVE_METHOD');json(200,await intakes.read(id));
148
- }
149
- return true;
150
- }
151
126
  if(match?.[2]==='review'&&req.method==='GET'){
152
- const review=await reviewForConnection();
153
127
  const candidate=url.searchParams.get('candidate');
154
128
  json(200,candidate?await review.candidate(match[1],candidate):url.searchParams.get('bundle')==='1'?await review.bundle(match[1]):await review.read(match[1]));
155
129
  return true;
156
130
  }
157
- if(req.method==='GET'){if(url.pathname==='/api/open'){const id=url.searchParams.get('project'),opened=await service.store.open(id);if(opened.project.base.kind!=='native-scene')return false;const result=await service.read(id);json(200,{...result,projectId:id,inputKind:'native-scene-document'});return true;}if(url.pathname==='/api/creation/capabilities'){const summary=url.searchParams.get('summary'),format=url.searchParams.get('format'),packsParam=url.searchParams.get('packs'),namesParam=url.searchParams.get('names');if(summary==='1'||summary==='true'){json(200,capabilitySummary());return true;}check(format===null||format==='full'||format==='compact','E_NATIVE_ARGUMENT');const packs=packsParam?packsParam.split(',').filter(Boolean):undefined,names=namesParam?namesParam.split(',').filter(Boolean):undefined;if(format==='compact'){json(200,compactCapabilities({packs,names}));return true;}if(names){const tools=new NativeAgentTools(service);json(200,await tools.run({command:'contracts',packs,names}));return true;}json(200,packs?capabilitiesForPacks(packs):capabilities());return true;}else if(url.pathname==='/api/projects'){const projects=await service.store.list();for(const p of projects)if(p.kind==='native-scene'){const r=await service.read(p.id);p.workingRevision=r.revisionId;}json(200,{projects});}else if(match?.[2]==='render')json(200,await service.render(match[1],url.searchParams.get('revision')));else if(match?.[2]?.startsWith('assets/')){const r=await service.read(match[1]),asset=r.project.assets.find(a=>a.id===match[2].slice(7));check(asset,'E_NATIVE_NOT_FOUND');json(200,asset);}else if(match&&!match[2]){const current=await service.read(match[1],url.searchParams.get('revision')??undefined);const tree=url.searchParams.get('tree');json(200,tree==='1'||tree==='true'?buildInspectTree(match[1],current,url.searchParams.get('sceneId')??undefined):current);}else check(false,'E_NATIVE_METHOD');return true;}
158
- check(req.method==='POST','E_NATIVE_METHOD');check(req.headers.origin==='http://127.0.0.1:'+port,'E_NATIVE_ORIGIN');check(req.headers['content-type']==='application/json','E_NATIVE_CONTENT_TYPE');req.setTimeout(10000,()=>req.destroy());let bytes=0;const chunks=[];const assetUpload=match?.[2]==='assets'||intake?.[2]==='assets',maxBytes=connectionRoute?8192:assetUpload?12*1024*1024:limits.transactionBytes;for await(const chunk of req){bytes+=chunk.length;check(bytes<=maxBytes,'E_NATIVE_SIZE');chunks.push(chunk);}req.setTimeout(0);const body=parseAuthoringJson(Buffer.concat(chunks).toString(),{bytes:maxBytes,nodes:limits.nodes,depth:limits.depth,allowNull:match?.[2]==='review'});
159
- if(connectionRoute){
160
- if(body.action==='disconnect'){
161
- check(exact(body,['action']),'E_NATIVE_ARGUMENT');
162
- json(200,await connection.disconnect());
163
- return true;
164
- }
165
- if(body.action==='models'){
166
- check(exact(body,['action','provider','apiKey','endpoint','preset']),'E_NATIVE_ARGUMENT');
167
- json(200,await connection.listModels({provider:body.provider,apiKey:body.apiKey,endpoint:body.endpoint,preset:body.preset}));
168
- return true;
169
- }
170
- if(Object.hasOwn(body,'provider')||Object.hasOwn(body,'model')){
171
- check(exact(body,['provider','model','apiKey','endpoint','preset','vision']),'E_NATIVE_ARGUMENT');
172
- json(200,await connection.save({provider:body.provider,model:body.model,apiKey:body.apiKey,endpoint:body.endpoint,preset:body.preset,vision:body.vision}));
173
- return true;
174
- }
175
- check(exact(body,['apiKey']),'E_NATIVE_ARGUMENT');
176
- json(200,await connection.save(body.apiKey));
131
+ if(req.method==='GET'){if(url.pathname==='/api/open'){const id=url.searchParams.get('project'),opened=await service.store.open(id);if(opened.project.base.kind!=='native-scene')return false;const result=await service.read(id);json(200,{...result,projectId:id,inputKind:'native-scene-document'});return true;}if(url.pathname==='/api/creation/capabilities'){const summary=url.searchParams.get('summary'),format=url.searchParams.get('format'),packsParam=url.searchParams.get('packs'),namesParam=url.searchParams.get('names');if(summary==='1'||summary==='true'){json(200,capabilitySummary());return true;}check(format===null||format==='full'||format==='compact','E_NATIVE_ARGUMENT');const packs=packsParam?packsParam.split(',').filter(Boolean):undefined,names=namesParam?namesParam.split(',').filter(Boolean):undefined;if(format==='compact'){json(200,compactCapabilities({packs,names}));return true;}if(names){const tools=new NativeAgentTools(service);json(200,await tools.run({command:'contracts',packs,names}));return true;}json(200,packs?capabilitiesForPacks(packs):capabilities());return true;}else if(url.pathname==='/api/projects'){const projects=await service.store.list();for(const p of projects)if(p.kind==='native-scene'){const r=await service.read(p.id);p.workingRevision=r.revisionId;}json(200,{projects});}else if(matrixJob){const job=matrixJobs.get(matrixJob[2]);check(job&&job.projectId===matrixJob[1],'E_NATIVE_NOT_FOUND');json(200,job);return true;}else if(match?.[2]==='budget'){const target=url.searchParams.get('target')??'standalone-browser-draft',variantId=url.searchParams.get('variant')??undefined,fitTargetBudget=url.searchParams.get('fit')==='1'||url.searchParams.get('fit')==='true';json(200,await service.estimateBudget(match[1],{target,variantId,revisionId:url.searchParams.get('revision')??undefined,fitTargetBudget}));}else if(match?.[2]==='variants'){const variantId=url.searchParams.get('variant');json(200,variantId?await service.diffVariant(match[1],variantId,{revisionId:url.searchParams.get('revision')??undefined}):await service.listVariants(match[1]));}else if(match?.[2]==='render')json(200,await service.render(match[1],url.searchParams.get('revision')));else if(match?.[2]?.startsWith('assets/')){const r=await service.read(match[1]),asset=r.project.assets.find(a=>a.id===match[2].slice(7));check(asset,'E_NATIVE_NOT_FOUND');json(200,asset);}else if(match&&!match[2]){const current=await service.read(match[1],url.searchParams.get('revision')??undefined);const tree=url.searchParams.get('tree');json(200,tree==='1'||tree==='true'?buildInspectTree(match[1],current,url.searchParams.get('sceneId')??undefined):current);}else check(false,'E_NATIVE_METHOD');return true;}
132
+ check(req.method==='POST','E_NATIVE_METHOD');check(req.headers.origin==='http://127.0.0.1:'+port,'E_NATIVE_ORIGIN');check(req.headers['content-type']==='application/json','E_NATIVE_CONTENT_TYPE');req.setTimeout(15000,()=>req.destroy());let bytes=0;const chunks=[];const assetUpload=match?.[2]==='assets',maxBytes=importProjectRoute?BUNDLE_LIMIT+1024*1024:assetUpload?12*1024*1024:limits.transactionBytes;for await(const chunk of req){bytes+=chunk.length;check(bytes<=maxBytes,'E_NATIVE_SIZE');chunks.push(chunk);}req.setTimeout(0);const body=parseAuthoringJson(Buffer.concat(chunks).toString(),{bytes:maxBytes,nodes:limits.nodes,depth:limits.depth,allowNull:match?.[2]==='review'});
133
+ if(startersComposeRoute){
134
+ check(exact(body,['starter','id','name','ctaLabel','winTitle','timeoutTitle','durationSeconds','winHoldSeconds','palette','androidUrl'])&&typeof body.starter==='string','E_NATIVE_ARGUMENT');
135
+ const resolvedId=body.id?String(body.id):await uniqueSlug(body.name||body.starter,body.starter);
136
+ const composed=await composeStarter({...body,id:resolvedId,deliver:false},{service,catalog:assetCatalog,remoteFetcher:cc0Fetcher,workspaceRoot:service.store.workspaceRoot});
137
+ const read=await service.read(composed.projectId);
138
+ json(201,{...composed,name:read.project.creativeBrief?.goal??body.name??composed.projectId,revisionId:read.revisionId,contentHash:read.contentHash});
177
139
  return true;
178
140
  }
179
- if(fromChatRoute){
180
- const {config:providerConfig}=await providerForConnection();
181
- json(201,await composeFromFreePack(service,body,{providerConfig,fetchImpl:connection.fetch}));
141
+ if(importProjectRoute){
142
+ check(exact(body,['bundleText','copy'])&&typeof body.bundleText==='string'&&body.bundleText.length>0&&(body.copy===undefined||typeof body.copy==='boolean'),'E_NATIVE_ARGUMENT');
143
+ let imported;
144
+ try{
145
+ imported=await importProjectFile(service,body.bundleText,{copy:body.copy!==false});
146
+ }catch(error){
147
+ if(/^E_[A-Z0-9_]+$/.test(error.message))throw error;
148
+ if(/exceeds 64 MiB/i.test(error.message??''))throw Error('E_BUNDLE_SIZE',{cause:error});
149
+ throw Error('E_BUNDLE_INVALID',{cause:error});
150
+ }
151
+ const read=await service.read(imported.projectId);
152
+ json(201,{...imported,name:read.project.creativeBrief?.goal??imported.projectId,revisionId:read.revisionId,contentHash:read.contentHash,editorUrl:'/?project='+encodeURIComponent(imported.projectId)});
182
153
  return true;
183
154
  }
184
155
  if(assetsFetchRoute){
@@ -196,29 +167,14 @@ export function nativeApi(service,connection=new ReviewConnection(service.store.
196
167
  json(200,await materializeDemo(service,body.id));
197
168
  return true;
198
169
  }
199
- if(intake){
200
- const [,id,route,assetId]=intake;
201
- check(!assetId,'E_NATIVE_METHOD');
202
- if(!id)json(201,await intakes.create(body));
203
- else if(route==='assets')json(201,await intakes.upload(id,body));
204
- else if(route==='submit')json(200,await intakes.submit(id,body));
205
- else if(route==='cancel'&&exact(body,[]))json(200,await intakes.cancel(id));
206
- else if(route==='retry'&&exact(body,[]))json(200,await intakes.retry(id));
207
- else check(false,'E_NATIVE_METHOD');
208
- return true;
209
- }
210
170
  if(url.pathname==='/api/projects'){check(body.kind===undefined||body.kind==='native-scene','E_NATIVE_KIND');json(201,await service.create(body));return true;}
211
171
  check(match,'E_NATIVE_NOT_FOUND');const [,id,route]=match;const fields={history:['expected','action'],accept:['revisionId','contentHash']}[route];if(fields)check(exact(body,fields)&&fields.every(key=>Object.hasOwn(body,key)),'E_NATIVE_ARGUMENT');
212
- if(route==='export')check(exact(body,['revisionId','target','fitTargetBudget'])&&Object.hasOwn(body,'revisionId')&&Object.hasOwn(body,'target')&&(body.fitTargetBudget===undefined||typeof body.fitTargetBudget==='boolean'),'E_NATIVE_ARGUMENT');
172
+ if(route==='export')check(exact(body,['revisionId','target','fitTargetBudget','variantId','confirmReviewed'])&&Object.hasOwn(body,'revisionId')&&Object.hasOwn(body,'target')&&(body.fitTargetBudget===undefined||typeof body.fitTargetBudget==='boolean'),'E_NATIVE_ARGUMENT');
173
+ if(route==='export-matrix')check(exact(body,['revisionId','variants','targets','fitTargetBudget','confirmReviewed','outputDir'])&&typeof body.revisionId==='string'&&Array.isArray(body.variants)&&Array.isArray(body.targets),'E_NATIVE_ARGUMENT');
174
+ if(route==='variants')check(exact(body,['action','variant','variantId','expectedVariantRevision','preset','id','label','language','texts','actionTexts','variables','storeUrl','direction','text'])&&['upsert','delete','preset'].includes(body.action),'E_NATIVE_ARGUMENT');
213
175
  if(route==='assets')check((exact(body,['expected','asset'])&&Object.hasOwn(body,'expected')&&Object.hasOwn(body,'asset'))||(exact(body,['expected','assets'])&&Object.hasOwn(body,'expected')&&Object.hasOwn(body,'assets')),'E_NATIVE_ARGUMENT');
214
176
  if(route==='stage-cc0')check(exact(body,['expected','items'])&&Object.hasOwn(body,'expected')&&Array.isArray(body.items),'E_NATIVE_ARGUMENT');
215
- if(route==='review'){
216
- const review=await reviewForConnection();
217
- const saved=await review.post(id,body);
218
- // Once a batch is received, processing belongs to the server, even if the tab closes.
219
- const start=body.action==='request'&&saved.status==='waiting'&&(review.configured||review.hasDeterministicIntent(saved));
220
- json(200,start?await review.resolve(id,saved.id):saved);
221
- }
177
+ if(route==='review')json(200,await review.post(id,body));
222
178
  else if(route==='transactions/preview'){const {project,...preview}=await service.preview(id,body);void project;json(200,preview);}
223
179
  else if(route==='transactions')json(201,await service.transact(id,body));
224
180
  else if(route==='assets')json(201,Array.isArray(body.assets)?await service.uploadBatch(id,body):await service.upload(id,body));
@@ -226,7 +182,65 @@ export function nativeApi(service,connection=new ReviewConnection(service.store.
226
182
  else if(route==='win-cue')json(201,await replaceProjectWinCue(service,id,body));
227
183
  else if(route==='history')json(200,await service.navigate(id,body));
228
184
  else if(route==='accept')json(200,await service.accept(id,body));
185
+ else if(route==='variants'){
186
+ if(body.action==='upsert')json(200,await service.upsertVariant(id,body.variant,{expectedVariantRevision:body.expectedVariantRevision}));
187
+ else if(body.action==='delete')json(200,await service.deleteVariant(id,body.variantId,{expectedVariantRevision:body.expectedVariantRevision}));
188
+ else json(201,await service.createPresetVariant(id,body));
189
+ }
190
+ else if(route==='export-matrix'){
191
+ const jobId=randomUUID(),requested=body.outputDir?resolve(service.store.workspaceRoot,body.outputDir):resolve(service.store.root,id,'exports',jobId),workspace=resolve(service.store.workspaceRoot);check(requested===workspace||requested.startsWith(workspace+sep),'E_AGENT_OUTPUT');
192
+ const job={projectId:id,jobId,status:'RUNNING',progress:[]};matrixJobs.set(jobId,job);json(202,{jobId,status:'RUNNING'});
193
+ void service.exportVariantMatrix(id,{...body,outputDir:requested,onProgress:progress=>{job.progress.push({...progress,at:Date.now()});}}).then(result=>{Object.assign(job,result);}).catch(error=>{job.status='FAILED';job.error=/^E_[A-Z0-9_]+$/.test(error.message)?error.message:'E_NATIVE_FAILED';}).finally(()=>{for(const [key,value]of matrixJobs)if(key!==jobId&&value.completedAt&&Date.now()-value.completedAt>3600000)matrixJobs.delete(key);job.completedAt=Date.now();});
194
+ }
195
+ else if(route==='quick-edit'){
196
+ check(exact(body,['expected','edits'])&&Object.hasOwn(body,'expected')&&Array.isArray(body.edits),'E_QUICK_EDIT_ARGUMENT');
197
+ const current=await service.read(id);
198
+ check(body.expected?.revisionId===current.revisionId&&body.expected?.contentHash===current.contentHash,'E_NATIVE_STALE');
199
+ const operations=buildQuickEditOperations(current.project,body.edits);
200
+ const envelope={format:'tora-transaction-1',expected:body.expected,operations};
201
+ const preview=await service.preview(id,envelope);
202
+ const committed=await service.transact(id,{...envelope,previewDigest:preview.previewDigest});
203
+ const updated=await service.read(id,committed.revisionId);
204
+ json(200,{revisionId:committed.revisionId,contentHash:committed.contentHash,quickEdit:summarizeQuickEdit(updated.project)});
205
+ }
206
+ else if(route==='qa'){
207
+ check(exact(body,['revisionId','target','variantId','fitTargetBudget']),'E_NATIVE_ARGUMENT');
208
+ const target=body.target??'standalone-browser-draft';
209
+ const variantId=body.variantId&&body.variantId!=='base'?body.variantId:undefined;
210
+ const fitTargetBudget=Boolean(body.fitTargetBudget);
211
+ const report=await service.runQa(id,{
212
+ revisionId:body.revisionId,
213
+ target,
214
+ variantId,
215
+ fitTargetBudget,
216
+ motionFilmstrip:true,
217
+ recordVideo:false,
218
+ });
219
+ const budget=await service.estimateBudget(id,{target,variantId,revisionId:body.revisionId,fitTargetBudget});
220
+ const qaRoot=resolve(service.store.root,id,'qa');
221
+ const assetUrl=relPath=>{
222
+ if(!relPath||!report.outputDir)return null;
223
+ const full=resolve(report.outputDir,relPath);
224
+ if(!full.startsWith(qaRoot+sep))return null;
225
+ const rel=relative(qaRoot,full).split(sep).join('/');
226
+ return `/api/projects/${encodeURIComponent(id)}/qa-asset?file=${encodeURIComponent(rel)}`;
227
+ };
228
+ const sheet=report.contactSheets?.find(item=>item.state==='all')??report.contactSheets?.[0];
229
+ const filmstrip=report.motionFilmstrips?.[0];
230
+ json(200,{
231
+ ok:Boolean(report.ok),
232
+ target,
233
+ bytes:budget.totalBytes,
234
+ cacheHit:Boolean(report.cacheHit),
235
+ blockers:report.blockers??[],
236
+ warnings:report.warnings??[],
237
+ checkedStates:report.summary?.checkedStates??[],
238
+ storeCta:report.checks?.browser?.storeCta??null,
239
+ contactSheetUrl:assetUrl(sheet?.path),
240
+ filmstripUrl:assetUrl(filmstrip?.path),
241
+ });
242
+ }
229
243
  else if(route==='export')json(200,await service.export(id,body));
230
244
  else check(false,'E_NATIVE_METHOD');return true;
231
- }catch(e){const code=/^E_[A-Z0-9_]+$/.test(e.message)?e.message:e.code==='EEXIST'?'E_NATIVE_EXISTS':e.code==='ENOENT'?'E_NATIVE_NOT_FOUND':'E_NATIVE_FAILED';const status=code.includes('STALE')||code.endsWith('EXISTS')?409:code.includes('ORIGIN')?403:code.includes('SIZE')||code.includes('LIMIT')?413:code.includes('NOT_FOUND')?404:code.startsWith('E_V2_')||code.includes('ENVELOPE')||code.includes('ARGUMENT')||code.includes('JSON')||code.includes('METHOD')||code.includes('CONTENT_TYPE')?400:422;json((connectionRoute&&connectionErrors[code])||status,{error:code,...(e.detail?{detail:e.detail}:{})});return true;}
245
+ }catch(e){const msg=String(e?.message??'');const code=/^E_[A-Z0-9_]+$/.test(msg)?msg:/Executable doesn't exist|playwright install|browserType\.launch/i.test(msg)?'E_CHROMIUM_MISSING':e.code==='EEXIST'?'E_NATIVE_EXISTS':e.code==='ENOENT'?'E_NATIVE_NOT_FOUND':'E_NATIVE_FAILED';const status=code.includes('STALE')||code.endsWith('EXISTS')?409:code.includes('ORIGIN')?403:code.includes('SIZE')||code.includes('LIMIT')?413:code.includes('NOT_FOUND')?404:code.startsWith('E_V2_')||code.includes('ENVELOPE')||code.includes('ARGUMENT')||code.includes('JSON')||code.includes('METHOD')||code.includes('CONTENT_TYPE')?400:422;json(status,{error:code,...(e.detail?{detail:e.detail}:{})});return true;}
232
246
  };}